blob: d0971fea482700a5dc1986f05af0cc0060f4a191 [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"
Jakob Stoklund Olesen8d0963f2010-12-21 01:50:21 +000027#include "llvm/Support/GraphWriter.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000028#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000031
32using namespace llvm;
33
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000034static cl::opt<bool>
35AllowSplit("spiller-splits-edges",
36 cl::desc("Allow critical edge splitting during spilling"));
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000037
38//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen8d0963f2010-12-21 01:50:21 +000039// Edge Bundles
40//===----------------------------------------------------------------------===//
41
42/// compute - Compute the edge bundles for MF. Bundles depend only on the CFG.
43void EdgeBundles::compute(const MachineFunction *mf) {
44 MF = mf;
45 EC.clear();
46 EC.grow(2 * MF->size());
47
48 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
49 ++I) {
50 const MachineBasicBlock &MBB = *I;
51 unsigned OutE = 2 * MBB.getNumber() + 1;
52 // Join the outgoing bundle with the ingoing bundles of all successors.
53 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
54 SE = MBB.succ_end(); SI != SE; ++SI)
55 EC.join(OutE, 2 * (*SI)->getNumber());
56 }
57 EC.compress();
58}
59
60/// view - Visualize the annotated bipartite CFG with Graphviz.
61void EdgeBundles::view() const {
62 ViewGraph(*this, "EdgeBundles");
63}
64
65/// Specialize WriteGraph, the standard implementation won't work.
66raw_ostream &llvm::WriteGraph(raw_ostream &O, const EdgeBundles &G,
67 bool ShortNames,
68 const std::string &Title) {
69 const MachineFunction *MF = G.getMachineFunction();
70
71 O << "digraph {\n";
72 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
73 I != E; ++I) {
74 unsigned BB = I->getNumber();
75 O << "\t\"BB#" << BB << "\" [ shape=box ]\n"
76 << '\t' << G.getBundle(BB, false) << " -> \"BB#" << BB << "\"\n"
77 << "\t\"BB#" << BB << "\" -> " << G.getBundle(BB, true) << '\n';
Jakob Stoklund Olesenc64379d2010-12-22 22:01:28 +000078 for (MachineBasicBlock::const_succ_iterator SI = I->succ_begin(),
79 SE = I->succ_end(); SI != SE; ++SI)
80 O << "\t\"BB#" << BB << "\" -> \"BB#" << (*SI)->getNumber()
81 << "\" [ color=lightgray ]\n";
Jakob Stoklund Olesen8d0963f2010-12-21 01:50:21 +000082 }
83 O << "}\n";
84 return O;
85}
86
87
88//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000089// Split Analysis
90//===----------------------------------------------------------------------===//
91
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000092SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
93 const LiveIntervals &lis,
94 const MachineLoopInfo &mli)
95 : mf_(mf),
96 lis_(lis),
97 loops_(mli),
98 tii_(*mf.getTarget().getInstrInfo()),
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000099 curli_(0) {}
100
101void SplitAnalysis::clear() {
102 usingInstrs_.clear();
103 usingBlocks_.clear();
104 usingLoops_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000105 curli_ = 0;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000106}
107
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000108bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
109 MachineBasicBlock *T, *F;
110 SmallVector<MachineOperand, 4> Cond;
111 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
112}
113
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000114/// analyzeUses - Count instructions, basic blocks, and loops using curli.
115void SplitAnalysis::analyzeUses() {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000116 const MachineRegisterInfo &MRI = mf_.getRegInfo();
117 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
118 MachineInstr *MI = I.skipInstruction();) {
119 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
120 continue;
121 MachineBasicBlock *MBB = MI->getParent();
122 if (usingBlocks_[MBB]++)
123 continue;
Jakob Stoklund Olesen9b90d7e2010-10-05 23:10:12 +0000124 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
125 Loop = Loop->getParentLoop())
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000126 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000127 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000128 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000129 << usingInstrs_.size() << " instrs, "
130 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000131 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000132}
133
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000134void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
135 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
136 unsigned count = usingBlocks_.lookup(*I);
137 OS << " BB#" << (*I)->getNumber();
138 if (count)
139 OS << '(' << count << ')';
140 }
141}
142
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000143// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
144// predecessor blocks, and exit blocks.
145void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
146 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000147
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000148 // Blocks in the loop.
149 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
150
151 // Predecessor blocks.
152 const MachineBasicBlock *Header = Loop->getHeader();
153 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
154 E = Header->pred_end(); I != E; ++I)
155 if (!Blocks.Loop.count(*I))
156 Blocks.Preds.insert(*I);
157
158 // Exit blocks.
159 for (MachineLoop::block_iterator I = Loop->block_begin(),
160 E = Loop->block_end(); I != E; ++I) {
161 const MachineBasicBlock *MBB = *I;
162 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
163 SE = MBB->succ_end(); SI != SE; ++SI)
164 if (!Blocks.Loop.count(*SI))
165 Blocks.Exits.insert(*SI);
166 }
167}
168
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000169void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
170 OS << "Loop:";
171 print(B.Loop, OS);
172 OS << ", preds:";
173 print(B.Preds, OS);
174 OS << ", exits:";
175 print(B.Exits, OS);
176}
177
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000178/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
179/// and around the Loop.
180SplitAnalysis::LoopPeripheralUse SplitAnalysis::
181analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000182 LoopPeripheralUse use = ContainedInLoop;
183 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
184 I != E; ++I) {
185 const MachineBasicBlock *MBB = I->first;
186 // Is this a peripheral block?
187 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000188 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000189 if (I->second > 1) use = MultiPeripheral;
190 else use = SinglePeripheral;
191 continue;
192 }
193 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000194 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000195 continue;
196 // It must be an unrelated block.
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000197 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000198 return OutsideLoop;
199 }
200 return use;
201}
202
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000203/// getCriticalExits - It may be necessary to partially break critical edges
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000204/// leaving the loop if an exit block has predecessors from outside the loop
205/// periphery.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000206void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
207 BlockPtrSet &CriticalExits) {
208 CriticalExits.clear();
209
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000210 // A critical exit block has curli live-in, and has a predecessor that is not
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000211 // in the loop nor a loop predecessor. For such an exit block, the edges
212 // carrying the new variable must be moved to a new pre-exit block.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000213 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
214 I != E; ++I) {
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000215 const MachineBasicBlock *Exit = *I;
216 // A single-predecessor exit block is definitely not a critical edge.
217 if (Exit->pred_size() == 1)
218 continue;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000219 // This exit may not have curli live in at all. No need to split.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000220 if (!lis_.isLiveInToMBB(*curli_, Exit))
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000221 continue;
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000222 // Does this exit block have a predecessor that is not a loop block or loop
223 // predecessor?
224 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
225 PE = Exit->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000226 const MachineBasicBlock *Pred = *PI;
227 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
228 continue;
229 // This is a critical exit block, and we need to split the exit edge.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000230 CriticalExits.insert(Exit);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000231 break;
232 }
233 }
234}
235
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000236void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
237 BlockPtrSet &CriticalPreds) {
238 CriticalPreds.clear();
239
240 // A critical predecessor block has curli live-out, and has a successor that
241 // has curli live-in and is not in the loop nor a loop exit block. For such a
242 // predecessor block, we must carry the value in both the 'inside' and
243 // 'outside' registers.
244 for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end();
245 I != E; ++I) {
246 const MachineBasicBlock *Pred = *I;
247 // Definitely not a critical edge.
248 if (Pred->succ_size() == 1)
249 continue;
250 // This block may not have curli live out at all if there is a PHI.
251 if (!lis_.isLiveOutOfMBB(*curli_, Pred))
252 continue;
253 // Does this block have a successor outside the loop?
254 for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(),
255 SE = Pred->succ_end(); SI != SE; ++SI) {
256 const MachineBasicBlock *Succ = *SI;
257 if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ))
258 continue;
259 if (!lis_.isLiveInToMBB(*curli_, Succ))
260 continue;
261 // This is a critical predecessor block.
262 CriticalPreds.insert(Pred);
263 break;
264 }
265 }
266}
267
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000268/// canSplitCriticalExits - Return true if it is possible to insert new exit
269/// blocks before the blocks in CriticalExits.
270bool
271SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
272 BlockPtrSet &CriticalExits) {
273 // If we don't allow critical edge splitting, require no critical exits.
274 if (!AllowSplit)
275 return CriticalExits.empty();
276
277 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
278 I != E; ++I) {
279 const MachineBasicBlock *Succ = *I;
280 // We want to insert a new pre-exit MBB before Succ, and change all the
281 // in-loop blocks to branch to the pre-exit instead of Succ.
282 // Check that all the in-loop predecessors can be changed.
283 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
284 PE = Succ->pred_end(); PI != PE; ++PI) {
285 const MachineBasicBlock *Pred = *PI;
286 // The external predecessors won't be altered.
287 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
288 continue;
289 if (!canAnalyzeBranch(Pred))
290 return false;
291 }
292
293 // If Succ's layout predecessor falls through, that too must be analyzable.
294 // We need to insert the pre-exit block in the gap.
295 MachineFunction::const_iterator MFI = Succ;
296 if (MFI == mf_.begin())
297 continue;
298 if (!canAnalyzeBranch(--MFI))
299 return false;
300 }
301 // No problems found.
302 return true;
303}
304
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000305void SplitAnalysis::analyze(const LiveInterval *li) {
306 clear();
307 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000308 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000309}
310
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000311void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
312 assert(curli_ && "Call analyze() before getSplitLoops");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000313 if (usingLoops_.empty())
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000314 return;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000315
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000316 LoopBlocks Blocks;
317 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000318
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000319 // We split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000320 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000321 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000322 const MachineLoop *Loop = I->first;
323 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000324 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000325
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000326 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000327 case OutsideLoop:
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000328 break;
329 case MultiPeripheral:
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000330 // FIXME: We could split a live range with multiple uses in a peripheral
331 // block and still make progress. However, it is possible that splitting
332 // another live range will insert copies into a peripheral block, and
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000333 // there is a small chance we can enter an infinite loop, inserting copies
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000334 // forever.
335 // For safety, stick to splitting live ranges with uses outside the
336 // periphery.
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000337 DEBUG(dbgs() << ": multiple peripheral uses");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000338 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000339 case ContainedInLoop:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000340 DEBUG(dbgs() << ": fully contained\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000341 continue;
342 case SinglePeripheral:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000343 DEBUG(dbgs() << ": single peripheral use\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000344 continue;
345 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000346 // Will it be possible to split around this loop?
347 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000348 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000349 if (!canSplitCriticalExits(Blocks, CriticalExits))
350 continue;
351 // This is a possible split.
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000352 Loops.insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000353 }
354
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000355 DEBUG(dbgs() << " getSplitLoops found " << Loops.size()
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000356 << " candidate loops.\n");
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000357}
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000358
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000359const MachineLoop *SplitAnalysis::getBestSplitLoop() {
360 LoopPtrSet Loops;
361 getSplitLoops(Loops);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000362 if (Loops.empty())
363 return 0;
364
365 // Pick the earliest loop.
366 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000367 const MachineLoop *Best = 0;
368 SlotIndex BestIdx;
369 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
370 ++I) {
371 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
372 if (!Best || Idx < BestIdx)
373 Best = *I, BestIdx = Idx;
374 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000375 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000376 return Best;
377}
378
Jakob Stoklund Olesen697483a2010-12-15 17:49:52 +0000379/// isBypassLoop - Return true if curli is live through Loop and has no uses
380/// inside the loop. Bypass loops are candidates for splitting because it can
381/// prevent interference inside the loop.
382bool SplitAnalysis::isBypassLoop(const MachineLoop *Loop) {
383 // If curli is live into the loop header and there are no uses in the loop, it
384 // must be live in the entire loop and live on at least one exiting edge.
385 return !usingLoops_.count(Loop) &&
386 lis_.isLiveInToMBB(*curli_, Loop->getHeader());
387}
388
389/// getBypassLoops - Get all the maximal bypass loops. These are the bypass
390/// loops whose parent is not a bypass loop.
391void SplitAnalysis::getBypassLoops(LoopPtrSet &BypassLoops) {
392 SmallVector<MachineLoop*, 8> Todo(loops_.begin(), loops_.end());
Jakob Stoklund Olesen62032952010-12-15 18:07:48 +0000393 while (!Todo.empty()) {
Jakob Stoklund Olesen697483a2010-12-15 17:49:52 +0000394 MachineLoop *Loop = Todo.pop_back_val();
395 if (!usingLoops_.count(Loop)) {
396 // This is either a bypass loop or completely irrelevant.
397 if (lis_.isLiveInToMBB(*curli_, Loop->getHeader()))
398 BypassLoops.insert(Loop);
399 // Either way, skip the child loops.
400 continue;
401 }
402
403 // The child loops may be bypass loops.
404 Todo.append(Loop->begin(), Loop->end());
405 }
406}
407
408
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000409//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000410// LiveIntervalMap
411//===----------------------------------------------------------------------===//
412
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000413// Work around the fact that the std::pair constructors are broken for pointer
414// pairs in some implementations. makeVV(x, 0) works.
415static inline std::pair<const VNInfo*, VNInfo*>
416makeVV(const VNInfo *a, VNInfo *b) {
417 return std::make_pair(a, b);
418}
419
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000420void LiveIntervalMap::reset(LiveInterval *li) {
421 li_ = li;
422 valueMap_.clear();
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000423 liveOutCache_.clear();
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000424}
425
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000426bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
427 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
428 return i != valueMap_.end() && i->second == 0;
429}
430
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000431// defValue - Introduce a li_ def for ParentVNI that could be later than
432// ParentVNI->def.
433VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000434 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000435 assert(ParentVNI && "Mapping NULL value");
436 assert(Idx.isValid() && "Invalid SlotIndex");
437 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
438
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000439 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000440 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000441
Jakob Stoklund Olesen79c02622010-10-26 22:36:02 +0000442 // Preserve the PHIDef bit.
443 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
444 VNI->setIsPHIDef(true);
445
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000446 // Use insert for lookup, so we can add missing values with a second lookup.
447 std::pair<ValueMap::iterator,bool> InsP =
448 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000449
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000450 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000451 if (!InsP.second)
452 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000453
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000454 return VNI;
455}
456
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000457
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000458// mapValue - Find the mapped value for ParentVNI at Idx.
459// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000460VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
461 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000462 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000463 assert(ParentVNI && "Mapping NULL value");
464 assert(Idx.isValid() && "Invalid SlotIndex");
465 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
466
467 // Use insert for lookup, so we can add missing values with a second lookup.
468 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000469 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000470
471 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000472 if (InsP.second) {
473 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000474 return InsP.first->second = li_->createValueCopy(ParentVNI,
475 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000476 }
477
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000478 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000479 if (InsP.first->second) {
480 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000481 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000482 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000483
484 // This is a complex mapped value. There may be multiple defs, and we may need
485 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000486 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000487 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
488 assert(IdxMBB && "No MBB at Idx");
489
490 // Is there a def in the same MBB we can extend?
491 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
492 return VNI;
493
494 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
495 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000496 // Perform a search for all predecessor blocks where we know the dominating
497 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
498 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
499 << " at " << Idx << " in " << *li_ << '\n');
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000500
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000501 // Blocks where li_ should be live-in.
502 SmallVector<MachineDomTreeNode*, 16> LiveIn;
503 LiveIn.push_back(mdt_[IdxMBB]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000504
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000505 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
506 for (unsigned i = 0; i != LiveIn.size(); ++i) {
507 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
508 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
509 PE = MBB->pred_end(); PI != PE; ++PI) {
510 MachineBasicBlock *Pred = *PI;
511 // Is this a known live-out block?
512 std::pair<LiveOutMap::iterator,bool> LOIP =
513 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
514 // Yes, we have been here before.
515 if (!LOIP.second) {
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000516 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
517 dbgs() << " known valno #" << VNI->id
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000518 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000519 continue;
520 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000521
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000522 // Does Pred provide a live-out value?
523 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
524 if (VNInfo *VNI = extendTo(Pred, Last)) {
525 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
526 DEBUG(dbgs() << " found valno #" << VNI->id
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000527 << " from BB#" << DefMBB->getNumber()
528 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000529 LiveOutPair &LOP = LOIP.first->second;
530 LOP.first = VNI;
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000531 LOP.second = mdt_[DefMBB];
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000532 continue;
533 }
534 // No, we need a live-in value for Pred as well
535 if (Pred != IdxMBB)
536 LiveIn.push_back(mdt_[Pred]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000537 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000538 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000539
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000540 // We may need to add phi-def values to preserve the SSA form.
541 // This is essentially the same iterative algorithm that SSAUpdater uses,
542 // except we already have a dominator tree, so we don't have to recompute it.
543 VNInfo *IdxVNI = 0;
544 unsigned Changes;
545 do {
546 Changes = 0;
547 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
548 // Propagate live-out values down the dominator tree, inserting phi-defs when
549 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
550 // likely for us to visit immediate dominators before their children.
551 for (unsigned i = LiveIn.size(); i; --i) {
552 MachineDomTreeNode *Node = LiveIn[i-1];
553 MachineBasicBlock *MBB = Node->getBlock();
554 MachineDomTreeNode *IDom = Node->getIDom();
555 LiveOutPair IDomValue;
556 // We need a live-in value to a block with no immediate dominator?
557 // This is probably an unreachable block that has survived somehow.
558 bool needPHI = !IDom;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000559
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000560 // Get the IDom live-out value.
561 if (!needPHI) {
562 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
563 if (I != liveOutCache_.end())
564 IDomValue = I->second;
565 else
566 // If IDom is outside our set of live-out blocks, there must be new
567 // defs, and we need a phi-def here.
568 needPHI = true;
569 }
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000570
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000571 // IDom dominates all of our predecessors, but it may not be the immediate
572 // dominator. Check if any of them have live-out values that are properly
573 // dominated by IDom. If so, we need a phi-def here.
574 if (!needPHI) {
575 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
576 PE = MBB->pred_end(); PI != PE; ++PI) {
577 LiveOutPair Value = liveOutCache_[*PI];
578 if (!Value.first || Value.first == IDomValue.first)
579 continue;
580 // This predecessor is carrying something other than IDomValue.
581 // It could be because IDomValue hasn't propagated yet, or it could be
582 // because MBB is in the dominance frontier of that value.
583 if (mdt_.dominates(IDom, Value.second)) {
584 needPHI = true;
585 break;
586 }
587 }
588 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000589
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000590 // Create a phi-def if required.
591 if (needPHI) {
592 ++Changes;
593 SlotIndex Start = lis_.getMBBStartIdx(MBB);
594 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
595 VNI->setIsPHIDef(true);
596 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
597 << " phi-def #" << VNI->id << " at " << Start << '\n');
598 // We no longer need li_ to be live-in.
599 LiveIn.erase(LiveIn.begin()+(i-1));
600 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
601 if (MBB == IdxMBB)
602 IdxVNI = VNI;
603 // Check if we need to update live-out info.
604 LiveOutMap::iterator I = liveOutCache_.find(MBB);
605 if (I == liveOutCache_.end() || I->second.second == Node) {
606 // We already have a live-out defined in MBB, so this must be IdxMBB.
607 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
608 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
609 } else {
610 // This phi-def is also live-out, so color the whole block.
611 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
612 I->second = LiveOutPair(VNI, Node);
613 }
614 } else if (IDomValue.first) {
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000615 // No phi-def here. Remember incoming value for IdxMBB.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000616 if (MBB == IdxMBB)
617 IdxVNI = IDomValue.first;
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000618 // Propagate IDomValue if needed:
619 // MBB is live-out and doesn't define its own value.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000620 LiveOutMap::iterator I = liveOutCache_.find(MBB);
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000621 if (I != liveOutCache_.end() && I->second.second != Node &&
622 I->second.first != IDomValue.first) {
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000623 ++Changes;
624 I->second = IDomValue;
625 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
626 << " idom valno #" << IDomValue.first->id
627 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
628 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000629 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000630 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000631 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
632 } while (Changes);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000633
634 assert(IdxVNI && "Didn't find value for Idx");
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000635
636#ifndef NDEBUG
637 // Check the liveOutCache_ invariants.
638 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
639 I != E; ++I) {
640 assert(I->first && "Null MBB entry in cache");
641 assert(I->second.first && "Null VNInfo in cache");
642 assert(I->second.second && "Null DomTreeNode in cache");
643 if (I->second.second->getBlock() == I->first)
644 continue;
645 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
646 PE = I->first->pred_end(); PI != PE; ++PI)
647 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
648 }
649#endif
650
651 // Since we went through the trouble of a full BFS visiting all reaching defs,
652 // the values in LiveIn are now accurate. No more phi-defs are needed
653 // for these blocks, so we can color the live ranges.
654 // This makes the next mapValue call much faster.
655 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
656 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
657 SlotIndex Start = lis_.getMBBStartIdx(MBB);
658 if (MBB == IdxMBB) {
659 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
660 continue;
661 }
662 // Anything in LiveIn other than IdxMBB is live-through.
663 VNInfo *VNI = liveOutCache_.lookup(MBB).first;
664 assert(VNI && "Missing block value");
665 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
666 }
667
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000668 return IdxVNI;
669}
670
671// extendTo - Find the last li_ value defined in MBB at or before Idx. The
672// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
673// Return the found VNInfo, or NULL.
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +0000674VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000675 assert(li_ && "call reset first");
676 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
677 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000678 return 0;
679 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000680 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000681 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000682 if (I->end <= Idx)
683 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000684 return I->valno;
685}
686
687// addSimpleRange - Add a simple range from parentli_ to li_.
688// ParentVNI must be live in the [Start;End) interval.
689void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
690 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000691 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000692 bool simple;
693 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
694 // A simple mapping is easy.
695 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000696 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000697 return;
698 }
699
700 // ParentVNI is a complex value. We must map per MBB.
701 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000702 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000703
704 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000705 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000706 return;
707 }
708
709 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000710 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000711
712 // Run sequence of full blocks.
713 for (++MBB; MBB != MBBE; ++MBB) {
714 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000715 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
716 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000717 }
718
719 // Final block.
720 Start = lis_.getMBBStartIdx(MBB);
721 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000722 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000723}
724
725/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
726/// All needed values whose def is not inside [Start;End) must be defined
727/// beforehand so mapValue will work.
728void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000729 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000730 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
731 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
732
733 // Check if --I begins before Start and overlaps.
734 if (I != B) {
735 --I;
736 if (I->end > Start)
737 addSimpleRange(Start, std::min(End, I->end), I->valno);
738 ++I;
739 }
740
741 // The remaining ranges begin after Start.
742 for (;I != E && I->start < End; ++I)
743 addSimpleRange(I->start, std::min(End, I->end), I->valno);
744}
745
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000746
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000747//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000748// Split Editor
749//===----------------------------------------------------------------------===//
750
751/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000752SplitEditor::SplitEditor(SplitAnalysis &sa,
753 LiveIntervals &lis,
754 VirtRegMap &vrm,
755 MachineDominatorTree &mdt,
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000756 LiveRangeEdit &edit)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000757 : sa_(sa), lis_(lis), vrm_(vrm),
758 mri_(vrm.getMachineFunction().getRegInfo()),
759 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000760 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000761 edit_(edit),
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000762 dupli_(lis_, mdt, edit.getParent()),
763 openli_(lis_, mdt, edit.getParent())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000764{
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000765 // We don't need an AliasAnalysis since we will only be performing
766 // cheap-as-a-copy remats anyway.
767 edit_.anyRematerializable(lis_, tii_, 0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000768}
769
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000770bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000771 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
772 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000773 return true;
774 return false;
775}
776
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000777VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
778 VNInfo *ParentVNI,
779 SlotIndex UseIdx,
780 MachineBasicBlock &MBB,
781 MachineBasicBlock::iterator I) {
782 VNInfo *VNI = 0;
783 MachineInstr *CopyMI = 0;
784 SlotIndex Def;
785
786 // Attempt cheap-as-a-copy rematerialization.
787 LiveRangeEdit::Remat RM(ParentVNI);
788 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
789 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
790 lis_, tii_, tri_);
791 } else {
792 // Can't remat, just insert a copy from parent.
793 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
794 Reg.getLI()->reg).addReg(edit_.getReg());
795 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
796 }
797
798 // Define the value in Reg.
799 VNI = Reg.defValue(ParentVNI, Def);
800 VNI->setCopy(CopyMI);
801
802 // Add minimal liveness for the new value.
803 if (UseIdx < Def)
804 UseIdx = Def;
805 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
806 return VNI;
807}
808
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000809/// Create a new virtual register and live interval.
810void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000811 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000812 if (!dupli_.getLI())
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000813 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000814
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000815 openli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000816}
817
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000818/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
819/// not live before Idx, a COPY is not inserted.
820void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000821 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000822 Idx = Idx.getUseIndex();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000823 DEBUG(dbgs() << " enterIntvBefore " << Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000824 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000825 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000826 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000827 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000828 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000829 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000830 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000831 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
832 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000833
834 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
835
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000836 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000837}
838
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000839/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000840void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000841 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000842 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000843 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000844 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000845 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000846 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000847 return;
848 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000849 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000850 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenb5f327b2010-11-10 23:56:00 +0000851 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000852 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000853}
854
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000855/// useIntv - indicate that all instructions in MBB should use openli.
856void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
857 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000858}
859
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000860void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000861 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000862 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000863 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
864 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000865}
866
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000867/// leaveIntvAfter - Leave openli after the instruction at Idx.
868void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000869 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000870 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000871
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000872 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000873 Idx = Idx.getBoundaryIndex();
874 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000875 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000876 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000877 return;
878 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000879 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000880
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000881 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000882 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
883 *MII->getParent(), llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000884
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000885 // Make sure that openli is properly extended from Idx to the new copy.
886 // FIXME: This shouldn't be necessary for remats.
887 openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
888
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000889 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000890}
891
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000892/// leaveIntvAtTop - Leave the interval at the top of MBB.
893/// Currently, only one value can leave the interval.
894void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000895 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000896 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000897 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000898
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000899 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000900 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000901 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000902 return;
903 }
904
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000905 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
906 MBB.SkipPHIsAndLabels(MBB.begin()));
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000907
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000908 // Finally we must make sure that openli is properly extended from Start to
909 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000910 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000911 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000912}
913
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000914/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000915/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000916void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000917 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000918
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000919 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000920 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000921 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000922}
923
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000924/// rewrite - Rewrite all uses of reg to use the new registers.
925void SplitEditor::rewrite(unsigned reg) {
926 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
927 RE = mri_.reg_end(); RI != RE;) {
928 MachineOperand &MO = RI.getOperand();
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000929 unsigned OpNum = RI.getOperandNo();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000930 MachineInstr *MI = MO.getParent();
931 ++RI;
932 if (MI->isDebugValue()) {
933 DEBUG(dbgs() << "Zapping " << *MI);
934 // FIXME: We can do much better with debug values.
935 MO.setReg(0);
936 continue;
937 }
938 SlotIndex Idx = lis_.getInstructionIndex(MI);
939 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
940 LiveInterval *LI = 0;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000941 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
942 ++I) {
943 LiveInterval *testli = *I;
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000944 if (testli->liveAt(Idx)) {
945 LI = testli;
946 break;
947 }
948 }
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000949 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000950 assert(LI && "No register was live at use");
951 MO.setReg(LI->reg);
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000952 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
953 MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000954 DEBUG(dbgs() << '\t' << *MI);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000955 }
956}
957
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000958void
959SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000960 // Build vector of iterator pairs from the intervals.
961 typedef std::pair<LiveInterval::const_iterator,
962 LiveInterval::const_iterator> IIPair;
963 SmallVector<IIPair, 8> Iters;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000964 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
965 ++LI) {
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000966 if (*LI == dupli_.getLI())
967 continue;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000968 LiveInterval::const_iterator I = (*LI)->find(Start);
969 LiveInterval::const_iterator E = (*LI)->end();
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000970 if (I != E)
971 Iters.push_back(std::make_pair(I, E));
972 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000973
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000974 SlotIndex sidx = Start;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000975 // Break [Start;End) into segments that don't overlap any intervals.
976 for (;;) {
977 SlotIndex next = sidx, eidx = End;
978 // Find overlapping intervals.
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000979 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
980 LiveInterval::const_iterator I = Iters[i].first;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000981 // Interval I is overlapping [sidx;eidx). Trim sidx.
982 if (I->start <= sidx) {
983 sidx = I->end;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000984 // Move to the next run, remove iters when all are consumed.
985 I = ++Iters[i].first;
986 if (I == Iters[i].second) {
987 Iters.erase(Iters.begin() + i);
988 --i;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000989 continue;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000990 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000991 }
992 // Trim eidx too if needed.
993 if (I->start >= eidx)
994 continue;
995 eidx = I->start;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000996 next = I->end;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000997 }
998 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
999 if (sidx < eidx)
1000 dupli_.addSimpleRange(sidx, eidx, VNI);
1001 // If the interval end was truncated, we can try again from next.
1002 if (next <= sidx)
1003 break;
1004 sidx = next;
1005 }
1006}
1007
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001008void SplitEditor::computeRemainder() {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001009 // First we need to fill in the live ranges in dupli.
1010 // If values were redefined, we need a full recoloring with SSA update.
1011 // If values were truncated, we only need to truncate the ranges.
1012 // If values were partially rematted, we should shrink to uses.
1013 // If values were fully rematted, they should be omitted.
1014 // FIXME: If a single value is redefined, just move the def and truncate.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +00001015 LiveInterval &parent = edit_.getParent();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001016
1017 // Values that are fully contained in the split intervals.
1018 SmallPtrSet<const VNInfo*, 8> deadValues;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001019 // Map all curli values that should have live defs in dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +00001020 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
1021 E = parent.vni_end(); I != E; ++I) {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001022 const VNInfo *VNI = *I;
Jakob Stoklund Olesen3ccfce02010-10-29 17:47:49 +00001023 // Don't transfer unused values to the new intervals.
1024 if (VNI->isUnused())
1025 continue;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001026 // Original def is contained in the split intervals.
1027 if (intervalsLiveAt(VNI->def)) {
1028 // Did this value escape?
1029 if (dupli_.isMapped(VNI))
1030 truncatedValues.insert(VNI);
1031 else
1032 deadValues.insert(VNI);
1033 continue;
1034 }
1035 // Add minimal live range at the definition.
1036 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
1037 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
1038 }
1039
1040 // Add all ranges to dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +00001041 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001042 I != E; ++I) {
1043 const LiveRange &LR = *I;
1044 if (truncatedValues.count(LR.valno)) {
1045 // recolor after removing intervals_.
1046 addTruncSimpleRange(LR.start, LR.end, LR.valno);
1047 } else if (!deadValues.count(LR.valno)) {
1048 // recolor without truncation.
1049 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
1050 }
1051 }
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +00001052
1053 // Extend dupli_ to be live out of any critical loop predecessors.
1054 // This means we have multiple registers live out of those blocks.
1055 // The alternative would be to split the critical edges.
1056 if (criticalPreds_.empty())
1057 return;
1058 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
1059 E = criticalPreds_.end(); I != E; ++I)
1060 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
1061 criticalPreds_.clear();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001062}
1063
1064void SplitEditor::finish() {
1065 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
1066 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
1067
1068 // Complete dupli liveness.
1069 computeRemainder();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001070
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +00001071 // Get rid of unused values and set phi-kill flags.
Jakob Stoklund Olesenf1354ae2010-10-26 22:36:05 +00001072 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
1073 (*I)->RenumberValues(lis_);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001074
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +00001075 // Rewrite instructions.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +00001076 rewrite(edit_.getReg());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001077
Jakob Stoklund Olesen3a0e0712010-10-26 22:36:09 +00001078 // Now check if any registers were separated into multiple components.
1079 ConnectedVNInfoEqClasses ConEQ(lis_);
1080 for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1081 // Don't use iterators, they are invalidated by create() below.
1082 LiveInterval *li = edit_.get(i);
1083 unsigned NumComp = ConEQ.Classify(li);
1084 if (NumComp <= 1)
1085 continue;
1086 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1087 SmallVector<LiveInterval*, 8> dups;
1088 dups.push_back(li);
1089 for (unsigned i = 1; i != NumComp; ++i)
1090 dups.push_back(&edit_.create(mri_, lis_, vrm_));
1091 ConEQ.Distribute(&dups[0]);
1092 // Rewrite uses to the new regs.
1093 rewrite(li->reg);
1094 }
1095
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001096 // Calculate spill weight and allocation hints for new intervals.
1097 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +00001098 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1099 LiveInterval &li = **I;
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +00001100 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001101 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001102 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
1103 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001104 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001105}
1106
1107
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001108//===----------------------------------------------------------------------===//
1109// Loop Splitting
1110//===----------------------------------------------------------------------===//
1111
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001112void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001113 SplitAnalysis::LoopBlocks Blocks;
1114 sa_.getLoopBlocks(Loop, Blocks);
1115
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001116 DEBUG({
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +00001117 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001118 });
1119
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001120 // Break critical edges as needed.
1121 SplitAnalysis::BlockPtrSet CriticalExits;
1122 sa_.getCriticalExits(Blocks, CriticalExits);
1123 assert(CriticalExits.empty() && "Cannot break critical exits yet");
1124
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +00001125 // Get critical predecessors so computeRemainder can deal with them.
1126 sa_.getCriticalPreds(Blocks, criticalPreds_);
1127
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001128 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001129 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001130
Jakob Stoklund Olesendfe3b6d2010-12-18 01:06:19 +00001131 // Insert copies in the predecessors if live-in to the header.
1132 if (lis_.isLiveInToMBB(edit_.getParent(), Loop->getHeader())) {
1133 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1134 E = Blocks.Preds.end(); I != E; ++I) {
1135 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1136 enterIntvAtEnd(MBB);
1137 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001138 }
1139
1140 // Switch all loop blocks.
1141 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1142 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001143 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001144
1145 // Insert back copies in the exit blocks.
1146 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1147 E = Blocks.Exits.end(); I != E; ++I) {
1148 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001149 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001150 }
1151
1152 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001153 closeIntv();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001154 finish();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001155}
1156
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001157
1158//===----------------------------------------------------------------------===//
1159// Single Block Splitting
1160//===----------------------------------------------------------------------===//
1161
Jakob Stoklund Olesen2bfb3242010-10-22 22:48:56 +00001162/// getMultiUseBlocks - if curli has more than one use in a basic block, it
1163/// may be an advantage to split curli for the duration of the block.
1164bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1165 // If curli is local to one block, there is no point to splitting it.
1166 if (usingBlocks_.size() <= 1)
1167 return false;
1168 // Add blocks with multiple uses.
1169 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1170 I != E; ++I)
1171 switch (I->second) {
1172 case 0:
1173 case 1:
1174 continue;
1175 case 2: {
1176 // When there are only two uses and curli is both live in and live out,
1177 // we don't really win anything by isolating the block since we would be
1178 // inserting two copies.
1179 // The remaing register would still have two uses in the block. (Unless it
1180 // separates into disconnected components).
1181 if (lis_.isLiveInToMBB(*curli_, I->first) &&
1182 lis_.isLiveOutOfMBB(*curli_, I->first))
1183 continue;
1184 } // Fall through.
1185 default:
1186 Blocks.insert(I->first);
1187 }
1188 return !Blocks.empty();
1189}
1190
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001191/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001192/// basic block in Blocks.
1193void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001194 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001195 // Determine the first and last instruction using curli in each block.
1196 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1197 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1198 IndexPairMap MBBRange;
1199 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1200 E = sa_.usingInstrs_.end(); I != E; ++I) {
1201 const MachineBasicBlock *MBB = (*I)->getParent();
1202 if (!Blocks.count(MBB))
1203 continue;
1204 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001205 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001206 IndexPair &IP = MBBRange[MBB];
1207 if (!IP.first.isValid() || Idx < IP.first)
1208 IP.first = Idx;
1209 if (!IP.second.isValid() || Idx > IP.second)
1210 IP.second = Idx;
1211 }
1212
1213 // Create a new interval for each block.
1214 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1215 E = Blocks.end(); I != E; ++I) {
1216 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001217 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001218 << IP.first << ';' << IP.second << ")\n");
1219 assert(IP.first.isValid() && IP.second.isValid());
1220
1221 openIntv();
1222 enterIntvBefore(IP.first);
1223 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1224 leaveIntvAfter(IP.second);
1225 closeIntv();
1226 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001227 finish();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001228}
1229
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001230
1231//===----------------------------------------------------------------------===//
1232// Sub Block Splitting
1233//===----------------------------------------------------------------------===//
1234
1235/// getBlockForInsideSplit - If curli is contained inside a single basic block,
1236/// and it wou pay to subdivide the interval inside that block, return it.
1237/// Otherwise return NULL. The returned block can be passed to
1238/// SplitEditor::splitInsideBlock.
1239const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1240 // The interval must be exclusive to one block.
1241 if (usingBlocks_.size() != 1)
1242 return 0;
1243 // Don't to this for less than 4 instructions. We want to be sure that
1244 // splitting actually reduces the instruction count per interval.
1245 if (usingInstrs_.size() < 4)
1246 return 0;
1247 return usingBlocks_.begin()->first;
1248}
1249
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001250/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1251void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001252 SmallVector<SlotIndex, 32> Uses;
1253 Uses.reserve(sa_.usingInstrs_.size());
1254 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1255 E = sa_.usingInstrs_.end(); I != E; ++I)
1256 if ((*I)->getParent() == MBB)
1257 Uses.push_back(lis_.getInstructionIndex(*I));
1258 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1259 << Uses.size() << " instructions.\n");
1260 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1261 array_pod_sort(Uses.begin(), Uses.end());
1262
1263 // Simple algorithm: Find the largest gap between uses as determined by slot
1264 // indices. Create new intervals for instructions before the gap and after the
1265 // gap.
1266 unsigned bestPos = 0;
1267 int bestGap = 0;
1268 DEBUG(dbgs() << " dist (" << Uses[0]);
1269 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1270 int g = Uses[i-1].distance(Uses[i]);
1271 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1272 if (g > bestGap)
1273 bestPos = i, bestGap = g;
1274 }
1275 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1276
1277 // bestPos points to the first use after the best gap.
1278 assert(bestPos > 0 && "Invalid gap");
1279
1280 // FIXME: Don't create intervals for low densities.
1281
1282 // First interval before the gap. Don't create single-instr intervals.
1283 if (bestPos > 1) {
1284 openIntv();
1285 enterIntvBefore(Uses.front());
1286 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1287 leaveIntvAfter(Uses[bestPos-1]);
1288 closeIntv();
1289 }
1290
1291 // Second interval after the gap.
1292 if (bestPos < Uses.size()-1) {
1293 openIntv();
1294 enterIntvBefore(Uses[bestPos]);
1295 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1296 leaveIntvAfter(Uses.back());
1297 closeIntv();
1298 }
1299
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001300 finish();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001301}