blob: fd18729b85b6479a25df42e5d94a1f246a042d71 [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
Jakob Stoklund Olesen376dcbd2010-11-03 20:39:23 +000015#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000016#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 Olesend68f4582010-10-28 20:34:50 +000021#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000022#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000025#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000028#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000030
31using namespace llvm;
32
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000033static cl::opt<bool>
34AllowSplit("spiller-splits-edges",
35 cl::desc("Allow critical edge splitting during spilling"));
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000036
37//===----------------------------------------------------------------------===//
38// Split Analysis
39//===----------------------------------------------------------------------===//
40
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000041SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
42 const LiveIntervals &lis,
43 const MachineLoopInfo &mli)
44 : mf_(mf),
45 lis_(lis),
46 loops_(mli),
47 tii_(*mf.getTarget().getInstrInfo()),
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000048 curli_(0) {}
49
50void SplitAnalysis::clear() {
51 usingInstrs_.clear();
52 usingBlocks_.clear();
53 usingLoops_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000054 curli_ = 0;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000055}
56
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000057bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
58 MachineBasicBlock *T, *F;
59 SmallVector<MachineOperand, 4> Cond;
60 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
61}
62
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +000063/// analyzeUses - Count instructions, basic blocks, and loops using curli.
64void SplitAnalysis::analyzeUses() {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000065 const MachineRegisterInfo &MRI = mf_.getRegInfo();
66 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
67 MachineInstr *MI = I.skipInstruction();) {
68 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
69 continue;
70 MachineBasicBlock *MBB = MI->getParent();
71 if (usingBlocks_[MBB]++)
72 continue;
Jakob Stoklund Olesen9b90d7e2010-10-05 23:10:12 +000073 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
74 Loop = Loop->getParentLoop())
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000075 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000076 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000077 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000078 << usingInstrs_.size() << " instrs, "
79 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000080 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000081}
82
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +000083void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
84 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
85 unsigned count = usingBlocks_.lookup(*I);
86 OS << " BB#" << (*I)->getNumber();
87 if (count)
88 OS << '(' << count << ')';
89 }
90}
91
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000092// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
93// predecessor blocks, and exit blocks.
94void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
95 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000096
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000097 // Blocks in the loop.
98 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
99
100 // Predecessor blocks.
101 const MachineBasicBlock *Header = Loop->getHeader();
102 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
103 E = Header->pred_end(); I != E; ++I)
104 if (!Blocks.Loop.count(*I))
105 Blocks.Preds.insert(*I);
106
107 // Exit blocks.
108 for (MachineLoop::block_iterator I = Loop->block_begin(),
109 E = Loop->block_end(); I != E; ++I) {
110 const MachineBasicBlock *MBB = *I;
111 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
112 SE = MBB->succ_end(); SI != SE; ++SI)
113 if (!Blocks.Loop.count(*SI))
114 Blocks.Exits.insert(*SI);
115 }
116}
117
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000118void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
119 OS << "Loop:";
120 print(B.Loop, OS);
121 OS << ", preds:";
122 print(B.Preds, OS);
123 OS << ", exits:";
124 print(B.Exits, OS);
125}
126
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000127/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
128/// and around the Loop.
129SplitAnalysis::LoopPeripheralUse SplitAnalysis::
130analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000131 LoopPeripheralUse use = ContainedInLoop;
132 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
133 I != E; ++I) {
134 const MachineBasicBlock *MBB = I->first;
135 // Is this a peripheral block?
136 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000137 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000138 if (I->second > 1) use = MultiPeripheral;
139 else use = SinglePeripheral;
140 continue;
141 }
142 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000143 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000144 continue;
145 // It must be an unrelated block.
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000146 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000147 return OutsideLoop;
148 }
149 return use;
150}
151
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000152/// getCriticalExits - It may be necessary to partially break critical edges
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000153/// leaving the loop if an exit block has predecessors from outside the loop
154/// periphery.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000155void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
156 BlockPtrSet &CriticalExits) {
157 CriticalExits.clear();
158
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000159 // A critical exit block has curli live-in, and has a predecessor that is not
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000160 // in the loop nor a loop predecessor. For such an exit block, the edges
161 // carrying the new variable must be moved to a new pre-exit block.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000162 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
163 I != E; ++I) {
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000164 const MachineBasicBlock *Exit = *I;
165 // A single-predecessor exit block is definitely not a critical edge.
166 if (Exit->pred_size() == 1)
167 continue;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000168 // This exit may not have curli live in at all. No need to split.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000169 if (!lis_.isLiveInToMBB(*curli_, Exit))
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000170 continue;
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000171 // Does this exit block have a predecessor that is not a loop block or loop
172 // predecessor?
173 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
174 PE = Exit->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000175 const MachineBasicBlock *Pred = *PI;
176 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
177 continue;
178 // This is a critical exit block, and we need to split the exit edge.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000179 CriticalExits.insert(Exit);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000180 break;
181 }
182 }
183}
184
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000185void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
186 BlockPtrSet &CriticalPreds) {
187 CriticalPreds.clear();
188
189 // A critical predecessor block has curli live-out, and has a successor that
190 // has curli live-in and is not in the loop nor a loop exit block. For such a
191 // predecessor block, we must carry the value in both the 'inside' and
192 // 'outside' registers.
193 for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end();
194 I != E; ++I) {
195 const MachineBasicBlock *Pred = *I;
196 // Definitely not a critical edge.
197 if (Pred->succ_size() == 1)
198 continue;
199 // This block may not have curli live out at all if there is a PHI.
200 if (!lis_.isLiveOutOfMBB(*curli_, Pred))
201 continue;
202 // Does this block have a successor outside the loop?
203 for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(),
204 SE = Pred->succ_end(); SI != SE; ++SI) {
205 const MachineBasicBlock *Succ = *SI;
206 if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ))
207 continue;
208 if (!lis_.isLiveInToMBB(*curli_, Succ))
209 continue;
210 // This is a critical predecessor block.
211 CriticalPreds.insert(Pred);
212 break;
213 }
214 }
215}
216
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000217/// canSplitCriticalExits - Return true if it is possible to insert new exit
218/// blocks before the blocks in CriticalExits.
219bool
220SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
221 BlockPtrSet &CriticalExits) {
222 // If we don't allow critical edge splitting, require no critical exits.
223 if (!AllowSplit)
224 return CriticalExits.empty();
225
226 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
227 I != E; ++I) {
228 const MachineBasicBlock *Succ = *I;
229 // We want to insert a new pre-exit MBB before Succ, and change all the
230 // in-loop blocks to branch to the pre-exit instead of Succ.
231 // Check that all the in-loop predecessors can be changed.
232 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
233 PE = Succ->pred_end(); PI != PE; ++PI) {
234 const MachineBasicBlock *Pred = *PI;
235 // The external predecessors won't be altered.
236 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
237 continue;
238 if (!canAnalyzeBranch(Pred))
239 return false;
240 }
241
242 // If Succ's layout predecessor falls through, that too must be analyzable.
243 // We need to insert the pre-exit block in the gap.
244 MachineFunction::const_iterator MFI = Succ;
245 if (MFI == mf_.begin())
246 continue;
247 if (!canAnalyzeBranch(--MFI))
248 return false;
249 }
250 // No problems found.
251 return true;
252}
253
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000254void SplitAnalysis::analyze(const LiveInterval *li) {
255 clear();
256 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000257 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000258}
259
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000260void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
261 assert(curli_ && "Call analyze() before getSplitLoops");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000262 if (usingLoops_.empty())
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000263 return;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000264
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000265 LoopBlocks Blocks;
266 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000267
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000268 // We split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000269 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000270 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000271 const MachineLoop *Loop = I->first;
272 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000273 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000274
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000275 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000276 case OutsideLoop:
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000277 break;
278 case MultiPeripheral:
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000279 // FIXME: We could split a live range with multiple uses in a peripheral
280 // block and still make progress. However, it is possible that splitting
281 // another live range will insert copies into a peripheral block, and
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000282 // there is a small chance we can enter an infinite loop, inserting copies
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000283 // forever.
284 // For safety, stick to splitting live ranges with uses outside the
285 // periphery.
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000286 DEBUG(dbgs() << ": multiple peripheral uses");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000287 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000288 case ContainedInLoop:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000289 DEBUG(dbgs() << ": fully contained\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000290 continue;
291 case SinglePeripheral:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000292 DEBUG(dbgs() << ": single peripheral use\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000293 continue;
294 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000295 // Will it be possible to split around this loop?
296 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000297 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000298 if (!canSplitCriticalExits(Blocks, CriticalExits))
299 continue;
300 // This is a possible split.
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000301 Loops.insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000302 }
303
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000304 DEBUG(dbgs() << " getSplitLoops found " << Loops.size()
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000305 << " candidate loops.\n");
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000306}
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000307
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000308const MachineLoop *SplitAnalysis::getBestSplitLoop() {
309 LoopPtrSet Loops;
310 getSplitLoops(Loops);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000311 if (Loops.empty())
312 return 0;
313
314 // Pick the earliest loop.
315 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000316 const MachineLoop *Best = 0;
317 SlotIndex BestIdx;
318 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
319 ++I) {
320 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
321 if (!Best || Idx < BestIdx)
322 Best = *I, BestIdx = Idx;
323 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000324 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000325 return Best;
326}
327
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000328//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000329// LiveIntervalMap
330//===----------------------------------------------------------------------===//
331
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000332// Work around the fact that the std::pair constructors are broken for pointer
333// pairs in some implementations. makeVV(x, 0) works.
334static inline std::pair<const VNInfo*, VNInfo*>
335makeVV(const VNInfo *a, VNInfo *b) {
336 return std::make_pair(a, b);
337}
338
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000339void LiveIntervalMap::reset(LiveInterval *li) {
340 li_ = li;
341 valueMap_.clear();
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000342 liveOutCache_.clear();
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000343}
344
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000345bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
346 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
347 return i != valueMap_.end() && i->second == 0;
348}
349
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000350// defValue - Introduce a li_ def for ParentVNI that could be later than
351// ParentVNI->def.
352VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000353 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000354 assert(ParentVNI && "Mapping NULL value");
355 assert(Idx.isValid() && "Invalid SlotIndex");
356 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
357
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000358 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000359 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000360
Jakob Stoklund Olesen79c02622010-10-26 22:36:02 +0000361 // Preserve the PHIDef bit.
362 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
363 VNI->setIsPHIDef(true);
364
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000365 // Use insert for lookup, so we can add missing values with a second lookup.
366 std::pair<ValueMap::iterator,bool> InsP =
367 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000368
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000369 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000370 if (!InsP.second)
371 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000372
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000373 return VNI;
374}
375
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000376
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000377// mapValue - Find the mapped value for ParentVNI at Idx.
378// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000379VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
380 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000381 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000382 assert(ParentVNI && "Mapping NULL value");
383 assert(Idx.isValid() && "Invalid SlotIndex");
384 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
385
386 // Use insert for lookup, so we can add missing values with a second lookup.
387 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000388 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000389
390 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000391 if (InsP.second) {
392 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000393 return InsP.first->second = li_->createValueCopy(ParentVNI,
394 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000395 }
396
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000397 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000398 if (InsP.first->second) {
399 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000400 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000401 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000402
403 // This is a complex mapped value. There may be multiple defs, and we may need
404 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000405 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000406 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
407 assert(IdxMBB && "No MBB at Idx");
408
409 // Is there a def in the same MBB we can extend?
410 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
411 return VNI;
412
413 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
414 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000415 // Perform a search for all predecessor blocks where we know the dominating
416 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
417 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
418 << " at " << Idx << " in " << *li_ << '\n');
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000419
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000420 // Blocks where li_ should be live-in.
421 SmallVector<MachineDomTreeNode*, 16> LiveIn;
422 LiveIn.push_back(mdt_[IdxMBB]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000423
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000424 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
425 for (unsigned i = 0; i != LiveIn.size(); ++i) {
426 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
427 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
428 PE = MBB->pred_end(); PI != PE; ++PI) {
429 MachineBasicBlock *Pred = *PI;
430 // Is this a known live-out block?
431 std::pair<LiveOutMap::iterator,bool> LOIP =
432 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
433 // Yes, we have been here before.
434 if (!LOIP.second) {
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000435 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
436 dbgs() << " known valno #" << VNI->id
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000437 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000438 continue;
439 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000440
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000441 // Does Pred provide a live-out value?
442 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
443 if (VNInfo *VNI = extendTo(Pred, Last)) {
444 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
445 DEBUG(dbgs() << " found valno #" << VNI->id
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000446 << " from BB#" << DefMBB->getNumber()
447 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000448 LiveOutPair &LOP = LOIP.first->second;
449 LOP.first = VNI;
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000450 LOP.second = mdt_[DefMBB];
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000451 continue;
452 }
453 // No, we need a live-in value for Pred as well
454 if (Pred != IdxMBB)
455 LiveIn.push_back(mdt_[Pred]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000456 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000457 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000458
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000459 // We may need to add phi-def values to preserve the SSA form.
460 // This is essentially the same iterative algorithm that SSAUpdater uses,
461 // except we already have a dominator tree, so we don't have to recompute it.
462 VNInfo *IdxVNI = 0;
463 unsigned Changes;
464 do {
465 Changes = 0;
466 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
467 // Propagate live-out values down the dominator tree, inserting phi-defs when
468 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
469 // likely for us to visit immediate dominators before their children.
470 for (unsigned i = LiveIn.size(); i; --i) {
471 MachineDomTreeNode *Node = LiveIn[i-1];
472 MachineBasicBlock *MBB = Node->getBlock();
473 MachineDomTreeNode *IDom = Node->getIDom();
474 LiveOutPair IDomValue;
475 // We need a live-in value to a block with no immediate dominator?
476 // This is probably an unreachable block that has survived somehow.
477 bool needPHI = !IDom;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000478
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000479 // Get the IDom live-out value.
480 if (!needPHI) {
481 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
482 if (I != liveOutCache_.end())
483 IDomValue = I->second;
484 else
485 // If IDom is outside our set of live-out blocks, there must be new
486 // defs, and we need a phi-def here.
487 needPHI = true;
488 }
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000489
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000490 // IDom dominates all of our predecessors, but it may not be the immediate
491 // dominator. Check if any of them have live-out values that are properly
492 // dominated by IDom. If so, we need a phi-def here.
493 if (!needPHI) {
494 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
495 PE = MBB->pred_end(); PI != PE; ++PI) {
496 LiveOutPair Value = liveOutCache_[*PI];
497 if (!Value.first || Value.first == IDomValue.first)
498 continue;
499 // This predecessor is carrying something other than IDomValue.
500 // It could be because IDomValue hasn't propagated yet, or it could be
501 // because MBB is in the dominance frontier of that value.
502 if (mdt_.dominates(IDom, Value.second)) {
503 needPHI = true;
504 break;
505 }
506 }
507 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000508
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000509 // Create a phi-def if required.
510 if (needPHI) {
511 ++Changes;
512 SlotIndex Start = lis_.getMBBStartIdx(MBB);
513 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
514 VNI->setIsPHIDef(true);
515 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
516 << " phi-def #" << VNI->id << " at " << Start << '\n');
517 // We no longer need li_ to be live-in.
518 LiveIn.erase(LiveIn.begin()+(i-1));
519 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
520 if (MBB == IdxMBB)
521 IdxVNI = VNI;
522 // Check if we need to update live-out info.
523 LiveOutMap::iterator I = liveOutCache_.find(MBB);
524 if (I == liveOutCache_.end() || I->second.second == Node) {
525 // We already have a live-out defined in MBB, so this must be IdxMBB.
526 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
527 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
528 } else {
529 // This phi-def is also live-out, so color the whole block.
530 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
531 I->second = LiveOutPair(VNI, Node);
532 }
533 } else if (IDomValue.first) {
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000534 // No phi-def here. Remember incoming value for IdxMBB.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000535 if (MBB == IdxMBB)
536 IdxVNI = IDomValue.first;
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000537 // Propagate IDomValue if needed:
538 // MBB is live-out and doesn't define its own value.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000539 LiveOutMap::iterator I = liveOutCache_.find(MBB);
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000540 if (I != liveOutCache_.end() && I->second.second != Node &&
541 I->second.first != IDomValue.first) {
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000542 ++Changes;
543 I->second = IDomValue;
544 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
545 << " idom valno #" << IDomValue.first->id
546 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
547 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000548 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000549 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000550 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
551 } while (Changes);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000552
553 assert(IdxVNI && "Didn't find value for Idx");
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000554
555#ifndef NDEBUG
556 // Check the liveOutCache_ invariants.
557 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
558 I != E; ++I) {
559 assert(I->first && "Null MBB entry in cache");
560 assert(I->second.first && "Null VNInfo in cache");
561 assert(I->second.second && "Null DomTreeNode in cache");
562 if (I->second.second->getBlock() == I->first)
563 continue;
564 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
565 PE = I->first->pred_end(); PI != PE; ++PI)
566 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
567 }
568#endif
569
570 // Since we went through the trouble of a full BFS visiting all reaching defs,
571 // the values in LiveIn are now accurate. No more phi-defs are needed
572 // for these blocks, so we can color the live ranges.
573 // This makes the next mapValue call much faster.
574 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
575 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
576 SlotIndex Start = lis_.getMBBStartIdx(MBB);
577 if (MBB == IdxMBB) {
578 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
579 continue;
580 }
581 // Anything in LiveIn other than IdxMBB is live-through.
582 VNInfo *VNI = liveOutCache_.lookup(MBB).first;
583 assert(VNI && "Missing block value");
584 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
585 }
586
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000587 return IdxVNI;
588}
589
590// extendTo - Find the last li_ value defined in MBB at or before Idx. The
591// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
592// Return the found VNInfo, or NULL.
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +0000593VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000594 assert(li_ && "call reset first");
595 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
596 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000597 return 0;
598 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000599 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000600 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000601 if (I->end <= Idx)
602 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000603 return I->valno;
604}
605
606// addSimpleRange - Add a simple range from parentli_ to li_.
607// ParentVNI must be live in the [Start;End) interval.
608void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
609 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000610 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000611 bool simple;
612 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
613 // A simple mapping is easy.
614 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000615 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000616 return;
617 }
618
619 // ParentVNI is a complex value. We must map per MBB.
620 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000621 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000622
623 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000624 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000625 return;
626 }
627
628 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000629 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000630
631 // Run sequence of full blocks.
632 for (++MBB; MBB != MBBE; ++MBB) {
633 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000634 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
635 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000636 }
637
638 // Final block.
639 Start = lis_.getMBBStartIdx(MBB);
640 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000641 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000642}
643
644/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
645/// All needed values whose def is not inside [Start;End) must be defined
646/// beforehand so mapValue will work.
647void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000648 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000649 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
650 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
651
652 // Check if --I begins before Start and overlaps.
653 if (I != B) {
654 --I;
655 if (I->end > Start)
656 addSimpleRange(Start, std::min(End, I->end), I->valno);
657 ++I;
658 }
659
660 // The remaining ranges begin after Start.
661 for (;I != E && I->start < End; ++I)
662 addSimpleRange(I->start, std::min(End, I->end), I->valno);
663}
664
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000665
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000666//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000667// Split Editor
668//===----------------------------------------------------------------------===//
669
670/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000671SplitEditor::SplitEditor(SplitAnalysis &sa,
672 LiveIntervals &lis,
673 VirtRegMap &vrm,
674 MachineDominatorTree &mdt,
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000675 LiveRangeEdit &edit)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000676 : sa_(sa), lis_(lis), vrm_(vrm),
677 mri_(vrm.getMachineFunction().getRegInfo()),
678 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000679 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000680 edit_(edit),
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000681 dupli_(lis_, mdt, edit.getParent()),
682 openli_(lis_, mdt, edit.getParent())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000683{
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000684 // We don't need an AliasAnalysis since we will only be performing
685 // cheap-as-a-copy remats anyway.
686 edit_.anyRematerializable(lis_, tii_, 0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000687}
688
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000689bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000690 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
691 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000692 return true;
693 return false;
694}
695
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000696VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
697 VNInfo *ParentVNI,
698 SlotIndex UseIdx,
699 MachineBasicBlock &MBB,
700 MachineBasicBlock::iterator I) {
701 VNInfo *VNI = 0;
702 MachineInstr *CopyMI = 0;
703 SlotIndex Def;
704
705 // Attempt cheap-as-a-copy rematerialization.
706 LiveRangeEdit::Remat RM(ParentVNI);
707 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
708 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
709 lis_, tii_, tri_);
710 } else {
711 // Can't remat, just insert a copy from parent.
712 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
713 Reg.getLI()->reg).addReg(edit_.getReg());
714 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
715 }
716
717 // Define the value in Reg.
718 VNI = Reg.defValue(ParentVNI, Def);
719 VNI->setCopy(CopyMI);
720
721 // Add minimal liveness for the new value.
722 if (UseIdx < Def)
723 UseIdx = Def;
724 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
725 return VNI;
726}
727
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000728/// Create a new virtual register and live interval.
729void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000730 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000731 if (!dupli_.getLI())
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000732 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000733
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000734 openli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000735}
736
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000737/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
738/// not live before Idx, a COPY is not inserted.
739void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000740 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000741 Idx = Idx.getUseIndex();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000742 DEBUG(dbgs() << " enterIntvBefore " << Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000743 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000744 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000745 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000746 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000747 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000748 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000749 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000750 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
751 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000752
753 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
754
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000755 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000756}
757
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000758/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000759void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000760 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000761 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000762 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000763 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000764 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000765 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000766 return;
767 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000768 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000769 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenb5f327b2010-11-10 23:56:00 +0000770 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000771 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000772}
773
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000774/// useIntv - indicate that all instructions in MBB should use openli.
775void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
776 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000777}
778
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000779void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000780 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000781 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000782 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
783 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000784}
785
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000786/// leaveIntvAfter - Leave openli after the instruction at Idx.
787void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000788 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000789 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000790
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000791 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000792 Idx = Idx.getBoundaryIndex();
793 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000794 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000795 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000796 return;
797 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000798 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000799
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000800 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000801 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
802 *MII->getParent(), llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000803
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000804 // Make sure that openli is properly extended from Idx to the new copy.
805 // FIXME: This shouldn't be necessary for remats.
806 openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
807
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000808 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000809}
810
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000811/// leaveIntvAtTop - Leave the interval at the top of MBB.
812/// Currently, only one value can leave the interval.
813void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000814 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000815 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000816 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000817
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000818 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000819 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000820 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000821 return;
822 }
823
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000824 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
825 MBB.SkipPHIsAndLabels(MBB.begin()));
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000826
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000827 // Finally we must make sure that openli is properly extended from Start to
828 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000829 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000830 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000831}
832
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000833/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000834/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000835void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000836 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000837
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000838 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000839 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000840 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000841}
842
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000843/// rewrite - Rewrite all uses of reg to use the new registers.
844void SplitEditor::rewrite(unsigned reg) {
845 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
846 RE = mri_.reg_end(); RI != RE;) {
847 MachineOperand &MO = RI.getOperand();
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000848 unsigned OpNum = RI.getOperandNo();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000849 MachineInstr *MI = MO.getParent();
850 ++RI;
851 if (MI->isDebugValue()) {
852 DEBUG(dbgs() << "Zapping " << *MI);
853 // FIXME: We can do much better with debug values.
854 MO.setReg(0);
855 continue;
856 }
857 SlotIndex Idx = lis_.getInstructionIndex(MI);
858 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
859 LiveInterval *LI = 0;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000860 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
861 ++I) {
862 LiveInterval *testli = *I;
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000863 if (testli->liveAt(Idx)) {
864 LI = testli;
865 break;
866 }
867 }
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000868 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000869 assert(LI && "No register was live at use");
870 MO.setReg(LI->reg);
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000871 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
872 MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000873 DEBUG(dbgs() << '\t' << *MI);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000874 }
875}
876
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000877void
878SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000879 // Build vector of iterator pairs from the intervals.
880 typedef std::pair<LiveInterval::const_iterator,
881 LiveInterval::const_iterator> IIPair;
882 SmallVector<IIPair, 8> Iters;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000883 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
884 ++LI) {
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000885 if (*LI == dupli_.getLI())
886 continue;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000887 LiveInterval::const_iterator I = (*LI)->find(Start);
888 LiveInterval::const_iterator E = (*LI)->end();
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000889 if (I != E)
890 Iters.push_back(std::make_pair(I, E));
891 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000892
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000893 SlotIndex sidx = Start;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000894 // Break [Start;End) into segments that don't overlap any intervals.
895 for (;;) {
896 SlotIndex next = sidx, eidx = End;
897 // Find overlapping intervals.
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000898 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
899 LiveInterval::const_iterator I = Iters[i].first;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000900 // Interval I is overlapping [sidx;eidx). Trim sidx.
901 if (I->start <= sidx) {
902 sidx = I->end;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000903 // Move to the next run, remove iters when all are consumed.
904 I = ++Iters[i].first;
905 if (I == Iters[i].second) {
906 Iters.erase(Iters.begin() + i);
907 --i;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000908 continue;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000909 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000910 }
911 // Trim eidx too if needed.
912 if (I->start >= eidx)
913 continue;
914 eidx = I->start;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000915 next = I->end;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000916 }
917 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
918 if (sidx < eidx)
919 dupli_.addSimpleRange(sidx, eidx, VNI);
920 // If the interval end was truncated, we can try again from next.
921 if (next <= sidx)
922 break;
923 sidx = next;
924 }
925}
926
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000927void SplitEditor::computeRemainder() {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000928 // First we need to fill in the live ranges in dupli.
929 // If values were redefined, we need a full recoloring with SSA update.
930 // If values were truncated, we only need to truncate the ranges.
931 // If values were partially rematted, we should shrink to uses.
932 // If values were fully rematted, they should be omitted.
933 // FIXME: If a single value is redefined, just move the def and truncate.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000934 LiveInterval &parent = edit_.getParent();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000935
936 // Values that are fully contained in the split intervals.
937 SmallPtrSet<const VNInfo*, 8> deadValues;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000938 // Map all curli values that should have live defs in dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000939 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
940 E = parent.vni_end(); I != E; ++I) {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000941 const VNInfo *VNI = *I;
Jakob Stoklund Olesen3ccfce02010-10-29 17:47:49 +0000942 // Don't transfer unused values to the new intervals.
943 if (VNI->isUnused())
944 continue;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000945 // Original def is contained in the split intervals.
946 if (intervalsLiveAt(VNI->def)) {
947 // Did this value escape?
948 if (dupli_.isMapped(VNI))
949 truncatedValues.insert(VNI);
950 else
951 deadValues.insert(VNI);
952 continue;
953 }
954 // Add minimal live range at the definition.
955 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
956 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
957 }
958
959 // Add all ranges to dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000960 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000961 I != E; ++I) {
962 const LiveRange &LR = *I;
963 if (truncatedValues.count(LR.valno)) {
964 // recolor after removing intervals_.
965 addTruncSimpleRange(LR.start, LR.end, LR.valno);
966 } else if (!deadValues.count(LR.valno)) {
967 // recolor without truncation.
968 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
969 }
970 }
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +0000971
972 // Extend dupli_ to be live out of any critical loop predecessors.
973 // This means we have multiple registers live out of those blocks.
974 // The alternative would be to split the critical edges.
975 if (criticalPreds_.empty())
976 return;
977 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
978 E = criticalPreds_.end(); I != E; ++I)
979 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
980 criticalPreds_.clear();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000981}
982
983void SplitEditor::finish() {
984 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
985 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
986
987 // Complete dupli liveness.
988 computeRemainder();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000989
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000990 // Get rid of unused values and set phi-kill flags.
Jakob Stoklund Olesenf1354ae2010-10-26 22:36:05 +0000991 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
992 (*I)->RenumberValues(lis_);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000993
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000994 // Rewrite instructions.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000995 rewrite(edit_.getReg());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000996
Jakob Stoklund Olesen3a0e0712010-10-26 22:36:09 +0000997 // Now check if any registers were separated into multiple components.
998 ConnectedVNInfoEqClasses ConEQ(lis_);
999 for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1000 // Don't use iterators, they are invalidated by create() below.
1001 LiveInterval *li = edit_.get(i);
1002 unsigned NumComp = ConEQ.Classify(li);
1003 if (NumComp <= 1)
1004 continue;
1005 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1006 SmallVector<LiveInterval*, 8> dups;
1007 dups.push_back(li);
1008 for (unsigned i = 1; i != NumComp; ++i)
1009 dups.push_back(&edit_.create(mri_, lis_, vrm_));
1010 ConEQ.Distribute(&dups[0]);
1011 // Rewrite uses to the new regs.
1012 rewrite(li->reg);
1013 }
1014
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001015 // Calculate spill weight and allocation hints for new intervals.
1016 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +00001017 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1018 LiveInterval &li = **I;
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +00001019 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001020 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001021 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
1022 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001023 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001024}
1025
1026
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001027//===----------------------------------------------------------------------===//
1028// Loop Splitting
1029//===----------------------------------------------------------------------===//
1030
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001031void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001032 SplitAnalysis::LoopBlocks Blocks;
1033 sa_.getLoopBlocks(Loop, Blocks);
1034
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001035 DEBUG({
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +00001036 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001037 });
1038
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001039 // Break critical edges as needed.
1040 SplitAnalysis::BlockPtrSet CriticalExits;
1041 sa_.getCriticalExits(Blocks, CriticalExits);
1042 assert(CriticalExits.empty() && "Cannot break critical exits yet");
1043
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +00001044 // Get critical predecessors so computeRemainder can deal with them.
1045 sa_.getCriticalPreds(Blocks, criticalPreds_);
1046
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001047 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001048 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001049
1050 // Insert copies in the predecessors.
1051 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1052 E = Blocks.Preds.end(); I != E; ++I) {
1053 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +00001054 enterIntvAtEnd(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001055 }
1056
1057 // Switch all loop blocks.
1058 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1059 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001060 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001061
1062 // Insert back copies in the exit blocks.
1063 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1064 E = Blocks.Exits.end(); I != E; ++I) {
1065 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001066 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001067 }
1068
1069 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001070 closeIntv();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001071 finish();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001072}
1073
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001074
1075//===----------------------------------------------------------------------===//
1076// Single Block Splitting
1077//===----------------------------------------------------------------------===//
1078
Jakob Stoklund Olesen2bfb3242010-10-22 22:48:56 +00001079/// getMultiUseBlocks - if curli has more than one use in a basic block, it
1080/// may be an advantage to split curli for the duration of the block.
1081bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1082 // If curli is local to one block, there is no point to splitting it.
1083 if (usingBlocks_.size() <= 1)
1084 return false;
1085 // Add blocks with multiple uses.
1086 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1087 I != E; ++I)
1088 switch (I->second) {
1089 case 0:
1090 case 1:
1091 continue;
1092 case 2: {
1093 // When there are only two uses and curli is both live in and live out,
1094 // we don't really win anything by isolating the block since we would be
1095 // inserting two copies.
1096 // The remaing register would still have two uses in the block. (Unless it
1097 // separates into disconnected components).
1098 if (lis_.isLiveInToMBB(*curli_, I->first) &&
1099 lis_.isLiveOutOfMBB(*curli_, I->first))
1100 continue;
1101 } // Fall through.
1102 default:
1103 Blocks.insert(I->first);
1104 }
1105 return !Blocks.empty();
1106}
1107
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001108/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001109/// basic block in Blocks.
1110void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001111 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001112 // Determine the first and last instruction using curli in each block.
1113 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1114 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1115 IndexPairMap MBBRange;
1116 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1117 E = sa_.usingInstrs_.end(); I != E; ++I) {
1118 const MachineBasicBlock *MBB = (*I)->getParent();
1119 if (!Blocks.count(MBB))
1120 continue;
1121 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001122 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001123 IndexPair &IP = MBBRange[MBB];
1124 if (!IP.first.isValid() || Idx < IP.first)
1125 IP.first = Idx;
1126 if (!IP.second.isValid() || Idx > IP.second)
1127 IP.second = Idx;
1128 }
1129
1130 // Create a new interval for each block.
1131 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1132 E = Blocks.end(); I != E; ++I) {
1133 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001134 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001135 << IP.first << ';' << IP.second << ")\n");
1136 assert(IP.first.isValid() && IP.second.isValid());
1137
1138 openIntv();
1139 enterIntvBefore(IP.first);
1140 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1141 leaveIntvAfter(IP.second);
1142 closeIntv();
1143 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001144 finish();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001145}
1146
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001147
1148//===----------------------------------------------------------------------===//
1149// Sub Block Splitting
1150//===----------------------------------------------------------------------===//
1151
1152/// getBlockForInsideSplit - If curli is contained inside a single basic block,
1153/// and it wou pay to subdivide the interval inside that block, return it.
1154/// Otherwise return NULL. The returned block can be passed to
1155/// SplitEditor::splitInsideBlock.
1156const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1157 // The interval must be exclusive to one block.
1158 if (usingBlocks_.size() != 1)
1159 return 0;
1160 // Don't to this for less than 4 instructions. We want to be sure that
1161 // splitting actually reduces the instruction count per interval.
1162 if (usingInstrs_.size() < 4)
1163 return 0;
1164 return usingBlocks_.begin()->first;
1165}
1166
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001167/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1168void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001169 SmallVector<SlotIndex, 32> Uses;
1170 Uses.reserve(sa_.usingInstrs_.size());
1171 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1172 E = sa_.usingInstrs_.end(); I != E; ++I)
1173 if ((*I)->getParent() == MBB)
1174 Uses.push_back(lis_.getInstructionIndex(*I));
1175 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1176 << Uses.size() << " instructions.\n");
1177 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1178 array_pod_sort(Uses.begin(), Uses.end());
1179
1180 // Simple algorithm: Find the largest gap between uses as determined by slot
1181 // indices. Create new intervals for instructions before the gap and after the
1182 // gap.
1183 unsigned bestPos = 0;
1184 int bestGap = 0;
1185 DEBUG(dbgs() << " dist (" << Uses[0]);
1186 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1187 int g = Uses[i-1].distance(Uses[i]);
1188 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1189 if (g > bestGap)
1190 bestPos = i, bestGap = g;
1191 }
1192 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1193
1194 // bestPos points to the first use after the best gap.
1195 assert(bestPos > 0 && "Invalid gap");
1196
1197 // FIXME: Don't create intervals for low densities.
1198
1199 // First interval before the gap. Don't create single-instr intervals.
1200 if (bestPos > 1) {
1201 openIntv();
1202 enterIntvBefore(Uses.front());
1203 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1204 leaveIntvAfter(Uses[bestPos-1]);
1205 closeIntv();
1206 }
1207
1208 // Second interval after the gap.
1209 if (bestPos < Uses.size()-1) {
1210 openIntv();
1211 enterIntvBefore(Uses[bestPos]);
1212 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1213 leaveIntvAfter(Uses.back());
1214 closeIntv();
1215 }
1216
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001217 finish();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001218}