1 //===-- PreAllocSplitting.cpp - Pre-allocation Interval Spltting Pass. ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the machine instruction level pre-register allocation
11 // live interval splitting pass. It finds live interval barriers, i.e.
12 // instructions which will kill all physical registers in certain register
13 // classes, and split all live intervals which cross the barrier.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "pre-alloc-split"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
39 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
41 STATISTIC(NumSplits, "Number of intervals split");
42 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
43 STATISTIC(NumFolds, "Number of intervals split with spill folding");
44 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
45 STATISTIC(NumDeadSpills, "Number of dead spills removed");
48 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
49 MachineFunction *CurrMF;
50 const TargetMachine *TM;
51 const TargetInstrInfo *TII;
52 MachineFrameInfo *MFI;
53 MachineRegisterInfo *MRI;
57 // Barrier - Current barrier being processed.
58 MachineInstr *Barrier;
60 // BarrierMBB - Basic block where the barrier resides in.
61 MachineBasicBlock *BarrierMBB;
63 // Barrier - Current barrier index.
66 // CurrLI - Current live interval being split.
69 // CurrSLI - Current stack slot live interval.
70 LiveInterval *CurrSLI;
72 // CurrSValNo - Current val# for the stack slot live interval.
75 // IntervalSSMap - A map from live interval to spill slots.
76 DenseMap<unsigned, int> IntervalSSMap;
78 // Def2SpillMap - A map from a def instruction index to spill index.
79 DenseMap<unsigned, unsigned> Def2SpillMap;
83 PreAllocSplitting() : MachineFunctionPass(&ID) {}
85 virtual bool runOnMachineFunction(MachineFunction &MF);
87 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.addRequired<LiveIntervals>();
89 AU.addPreserved<LiveIntervals>();
90 AU.addRequired<LiveStacks>();
91 AU.addPreserved<LiveStacks>();
92 AU.addPreserved<RegisterCoalescer>();
94 AU.addPreservedID(StrongPHIEliminationID);
96 AU.addPreservedID(PHIEliminationID);
97 AU.addRequired<MachineDominatorTree>();
98 AU.addRequired<MachineLoopInfo>();
99 AU.addPreserved<MachineDominatorTree>();
100 AU.addPreserved<MachineLoopInfo>();
101 MachineFunctionPass::getAnalysisUsage(AU);
104 virtual void releaseMemory() {
105 IntervalSSMap.clear();
106 Def2SpillMap.clear();
109 virtual const char *getPassName() const {
110 return "Pre-Register Allocaton Live Interval Splitting";
113 /// print - Implement the dump method.
114 virtual void print(std::ostream &O, const Module* M = 0) const {
118 void print(std::ostream *O, const Module* M = 0) const {
123 MachineBasicBlock::iterator
124 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
127 MachineBasicBlock::iterator
128 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
129 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
131 MachineBasicBlock::iterator
132 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
133 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
135 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
137 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
138 unsigned&, int&) const;
140 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
142 VNInfo* UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
144 bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
145 SmallVector<MachineOperand*, 4>&,
146 SmallPtrSet<MachineInstr*, 4>&);
148 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
149 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
150 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
151 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
152 SmallVector<MachineBasicBlock*, 4>&);
154 bool SplitRegLiveInterval(LiveInterval*);
156 bool SplitRegLiveIntervals(const TargetRegisterClass **,
157 SmallPtrSet<LiveInterval*, 8>&);
159 void RepairLiveInterval(LiveInterval* CurrLI, VNInfo* ValNo,
160 MachineInstr* DefMI, unsigned RestoreIdx);
162 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
163 MachineBasicBlock* BarrierMBB);
164 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
166 MachineBasicBlock::iterator RestorePt,
168 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
169 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
171 MachineInstr* Barrier,
172 MachineBasicBlock* MBB,
174 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
175 void RenumberValno(VNInfo* VN);
176 void ReconstructLiveInterval(LiveInterval* LI);
177 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
178 unsigned getNumberOfSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
179 unsigned Reg, int FrameIndex);
180 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator use,
181 MachineBasicBlock* MBB,
183 SmallPtrSet<MachineInstr*, 4>& Visited,
184 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
185 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
186 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
187 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
188 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
189 bool toplevel, bool intrablock);
191 } // end anonymous namespace
193 char PreAllocSplitting::ID = 0;
195 static RegisterPass<PreAllocSplitting>
196 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
198 const PassInfo *const llvm::PreAllocSplittingID = &X;
201 /// findNextEmptySlot - Find a gap after the given machine instruction in the
202 /// instruction index map. If there isn't one, return end().
203 MachineBasicBlock::iterator
204 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
205 unsigned &SpotIndex) {
206 MachineBasicBlock::iterator MII = MI;
207 if (++MII != MBB->end()) {
208 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
217 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
218 /// for spilling the current live interval. The index must be before any
219 /// defs and uses of the live interval register in the mbb. Return begin() if
221 MachineBasicBlock::iterator
222 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
224 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
225 unsigned &SpillIndex) {
226 MachineBasicBlock::iterator Pt = MBB->begin();
228 // Go top down if RefsInMBB is empty.
229 if (RefsInMBB.empty() && !DefMI) {
230 MachineBasicBlock::iterator MII = MBB->begin();
231 MachineBasicBlock::iterator EndPt = MI;
234 unsigned Index = LIs->getInstructionIndex(MII);
235 unsigned Gap = LIs->findGapBeforeInstr(Index);
241 } while (MII != EndPt);
243 MachineBasicBlock::iterator MII = MI;
244 MachineBasicBlock::iterator EndPt = DefMI
245 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
246 while (MII != EndPt && !RefsInMBB.count(MII)) {
247 unsigned Index = LIs->getInstructionIndex(MII);
248 if (LIs->hasGapBeforeInstr(Index)) {
250 SpillIndex = LIs->findGapBeforeInstr(Index, true);
259 /// findRestorePoint - Find a gap in the instruction index map that's suitable
260 /// for restoring the current live interval value. The index must be before any
261 /// uses of the live interval register in the mbb. Return end() if none is
263 MachineBasicBlock::iterator
264 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
266 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
267 unsigned &RestoreIndex) {
268 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
269 // begin index accordingly.
270 MachineBasicBlock::iterator Pt = MBB->end();
271 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
273 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
274 // the last index in the live range.
275 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
276 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
277 MachineBasicBlock::iterator EndPt = MI;
280 unsigned Index = LIs->getInstructionIndex(MII);
281 unsigned Gap = LIs->findGapBeforeInstr(Index);
288 } while (MII != EndPt);
290 MachineBasicBlock::iterator MII = MI;
292 // FIXME: Limit the number of instructions to examine to reduce
294 while (MII != MBB->end()) {
295 unsigned Index = LIs->getInstructionIndex(MII);
298 unsigned Gap = LIs->findGapBeforeInstr(Index);
303 if (RefsInMBB.count(MII))
312 /// CreateSpillStackSlot - Create a stack slot for the live interval being
313 /// split. If the live interval was previously split, just reuse the same
315 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
316 const TargetRegisterClass *RC) {
318 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
319 if (I != IntervalSSMap.end()) {
322 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
323 IntervalSSMap[Reg] = SS;
326 // Create live interval for stack slot.
327 CurrSLI = &LSs->getOrCreateInterval(SS);
328 if (CurrSLI->hasAtLeastOneValue())
329 CurrSValNo = CurrSLI->getValNumInfo(0);
331 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
335 /// IsAvailableInStack - Return true if register is available in a split stack
336 /// slot at the specified index.
338 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
339 unsigned Reg, unsigned DefIndex,
340 unsigned RestoreIndex, unsigned &SpillIndex,
345 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
346 if (I == IntervalSSMap.end())
348 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
349 if (II == Def2SpillMap.end())
352 // If last spill of def is in the same mbb as barrier mbb (where restore will
353 // be), make sure it's not below the intended restore index.
354 // FIXME: Undo the previous spill?
355 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
356 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
360 SpillIndex = II->second;
364 /// UpdateSpillSlotInterval - Given the specified val# of the register live
365 /// interval being split, and the spill and restore indicies, update the live
366 /// interval of the spill stack slot.
368 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
369 unsigned RestoreIndex) {
370 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
371 "Expect restore in the barrier mbb");
373 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
374 if (MBB == BarrierMBB) {
375 // Intra-block spill + restore. We are done.
376 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
377 CurrSLI->addRange(SLR);
381 SmallPtrSet<MachineBasicBlock*, 4> Processed;
382 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
383 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
384 CurrSLI->addRange(SLR);
385 Processed.insert(MBB);
387 // Start from the spill mbb, figure out the extend of the spill slot's
389 SmallVector<MachineBasicBlock*, 4> WorkList;
390 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
391 if (LR->end > EndIdx)
392 // If live range extend beyond end of mbb, add successors to work list.
393 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
394 SE = MBB->succ_end(); SI != SE; ++SI)
395 WorkList.push_back(*SI);
397 while (!WorkList.empty()) {
398 MachineBasicBlock *MBB = WorkList.back();
400 if (Processed.count(MBB))
402 unsigned Idx = LIs->getMBBStartIdx(MBB);
403 LR = CurrLI->getLiveRangeContaining(Idx);
404 if (LR && LR->valno == ValNo) {
405 EndIdx = LIs->getMBBEndIdx(MBB);
406 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
407 // Spill slot live interval stops at the restore.
408 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
409 CurrSLI->addRange(SLR);
410 } else if (LR->end > EndIdx) {
411 // Live range extends beyond end of mbb, process successors.
412 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
413 CurrSLI->addRange(SLR);
414 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
415 SE = MBB->succ_end(); SI != SE; ++SI)
416 WorkList.push_back(*SI);
418 LiveRange SLR(Idx, LR->end, CurrSValNo);
419 CurrSLI->addRange(SLR);
421 Processed.insert(MBB);
426 /// UpdateRegisterInterval - Given the specified val# of the current live
427 /// interval is being split, and the spill and restore indices, update the live
428 /// interval accordingly.
430 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
431 unsigned RestoreIndex) {
432 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
433 "Expect restore in the barrier mbb");
435 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
436 SmallVector<std::pair<unsigned,unsigned>, 4> After;
437 SmallVector<unsigned, 4> BeforeKills;
438 SmallVector<unsigned, 4> AfterKills;
439 SmallPtrSet<const LiveRange*, 4> Processed;
441 // First, let's figure out which parts of the live interval is now defined
442 // by the restore, which are defined by the original definition.
443 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
444 After.push_back(std::make_pair(RestoreIndex, LR->end));
445 if (CurrLI->isKill(ValNo, LR->end))
446 AfterKills.push_back(LR->end);
448 assert(LR->contains(SpillIndex));
449 if (SpillIndex > LR->start) {
450 Before.push_back(std::make_pair(LR->start, SpillIndex));
451 BeforeKills.push_back(SpillIndex);
453 Processed.insert(LR);
455 // Start from the restore mbb, figure out what part of the live interval
456 // are defined by the restore.
457 SmallVector<MachineBasicBlock*, 4> WorkList;
458 MachineBasicBlock *MBB = BarrierMBB;
459 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
460 SE = MBB->succ_end(); SI != SE; ++SI)
461 WorkList.push_back(*SI);
463 SmallPtrSet<MachineBasicBlock*, 4> ProcessedBlocks;
464 ProcessedBlocks.insert(MBB);
466 while (!WorkList.empty()) {
467 MBB = WorkList.back();
469 unsigned Idx = LIs->getMBBStartIdx(MBB);
470 LR = CurrLI->getLiveRangeContaining(Idx);
471 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
472 After.push_back(std::make_pair(LR->start, LR->end));
473 if (CurrLI->isKill(ValNo, LR->end))
474 AfterKills.push_back(LR->end);
475 Idx = LIs->getMBBEndIdx(MBB);
477 // Live range extend beyond at least one mbb. Let's see what other
479 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
481 Processed.insert(LR);
484 ProcessedBlocks.insert(MBB);
486 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
487 SE = MBB->succ_end(); SI != SE; ++SI)
488 if (!ProcessedBlocks.count(*SI))
489 WorkList.push_back(*SI);
492 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
495 if (LR->valno == ValNo && !Processed.count(LR)) {
496 Before.push_back(std::make_pair(LR->start, LR->end));
497 if (CurrLI->isKill(ValNo, LR->end))
498 BeforeKills.push_back(LR->end);
502 // Now create new val#s to represent the live ranges defined by the old def
503 // those defined by the restore.
504 unsigned AfterDef = ValNo->def;
505 MachineInstr *AfterCopy = ValNo->copy;
506 bool HasPHIKill = ValNo->hasPHIKill;
507 CurrLI->removeValNo(ValNo);
508 VNInfo *BValNo = (Before.empty())
510 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
512 CurrLI->addKills(BValNo, BeforeKills);
514 VNInfo *AValNo = (After.empty())
516 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
518 AValNo->hasPHIKill = HasPHIKill;
519 CurrLI->addKills(AValNo, AfterKills);
522 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
523 unsigned Start = Before[i].first;
524 unsigned End = Before[i].second;
525 CurrLI->addRange(LiveRange(Start, End, BValNo));
527 for (unsigned i = 0, e = After.size(); i != e; ++i) {
528 unsigned Start = After[i].first;
529 unsigned End = After[i].second;
530 CurrLI->addRange(LiveRange(Start, End, AValNo));
536 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
537 /// given block, shrink wrap the live interval to the last use (i.e. remove
538 /// from last use to the end of the mbb). In case mbb is the where the barrier
539 /// is, remove from the last use to the barrier.
541 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
542 SmallVector<MachineOperand*, 4> &Uses,
543 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
544 MachineOperand *LastMO = 0;
545 MachineInstr *LastMI = 0;
546 if (MBB != BarrierMBB && Uses.size() == 1) {
547 // Single use, no need to traverse the block. We can't assume this for the
548 // barrier bb though since the use is probably below the barrier.
550 LastMI = LastMO->getParent();
552 MachineBasicBlock::iterator MEE = MBB->begin();
553 MachineBasicBlock::iterator MII;
554 if (MBB == BarrierMBB)
560 MachineInstr *UseMI = &*MII;
561 if (!UseMIs.count(UseMI))
563 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
564 MachineOperand &MO = UseMI->getOperand(i);
565 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
575 // Cut off live range from last use (or beginning of the mbb if there
576 // are no uses in it) to the end of the mbb.
577 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
579 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
580 assert(!LastMO->isKill() && "Last use already terminates the interval?");
583 assert(MBB == BarrierMBB);
584 RangeStart = LIs->getMBBStartIdx(MBB);
586 if (MBB == BarrierMBB)
587 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
588 CurrLI->removeRange(RangeStart, RangeEnd);
590 CurrLI->addKill(ValNo, RangeStart);
592 // Return true if the last use becomes a new kill.
596 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
597 /// construction algorithm to compute the ranges and valnos for an interval.
598 VNInfo* PreAllocSplitting::PerformPHIConstruction(
599 MachineBasicBlock::iterator use,
600 MachineBasicBlock* MBB,
602 SmallPtrSet<MachineInstr*, 4>& Visited,
603 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
604 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
605 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
606 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
607 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
608 bool toplevel, bool intrablock) {
609 // Return memoized result if it's available.
610 if (toplevel && Visited.count(use) && NewVNs.count(use))
612 else if (!toplevel && intrablock && NewVNs.count(use))
614 else if (!intrablock && LiveOut.count(MBB))
617 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
619 // Check if our block contains any uses or defs.
620 bool ContainsDefs = Defs.count(MBB);
621 bool ContainsUses = Uses.count(MBB);
625 // Enumerate the cases of use/def contaning blocks.
626 if (!ContainsDefs && !ContainsUses) {
628 // NOTE: Because this is the fallback case from other cases, we do NOT
629 // assume that we are not intrablock here.
630 if (Phis.count(MBB)) return Phis[MBB];
632 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
634 if (MBB->pred_size() == 1) {
635 Phis[MBB] = ret = PerformPHIConstruction((*MBB->pred_begin())->end(),
636 *(MBB->pred_begin()), LI, Visited,
637 Defs, Uses, NewVNs, LiveOut, Phis,
639 unsigned EndIndex = 0;
641 EndIndex = LIs->getInstructionIndex(use);
642 EndIndex = LiveIntervals::getUseIndex(EndIndex);
644 EndIndex = LIs->getMBBEndIdx(MBB);
646 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
648 LI->addKill(ret, EndIndex);
650 Phis[MBB] = ret = LI->getNextValue(~0U, /*FIXME*/ 0,
651 LIs->getVNInfoAllocator());
652 if (!intrablock) LiveOut[MBB] = ret;
654 // If there are no uses or defs between our starting point and the
655 // beginning of the block, then recursive perform phi construction
656 // on our predecessors.
657 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
658 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
659 PE = MBB->pred_end(); PI != PE; ++PI) {
660 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
661 Visited, Defs, Uses, NewVNs,
662 LiveOut, Phis, false, false);
664 IncomingVNs[*PI] = Incoming;
667 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
668 // VNInfo to represent the joined value.
669 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
670 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
671 I->second->hasPHIKill = true;
672 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
673 LI->addKill(I->second, KillIndex);
676 unsigned EndIndex = 0;
678 EndIndex = LIs->getInstructionIndex(use);
679 EndIndex = LiveIntervals::getUseIndex(EndIndex);
681 EndIndex = LIs->getMBBEndIdx(MBB);
682 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
684 LI->addKill(ret, EndIndex);
686 } else if (ContainsDefs && !ContainsUses) {
687 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
689 // Search for the def in this block. If we don't find it before the
690 // instruction we care about, go to the fallback case. Note that that
691 // should never happen: this cannot be intrablock, so use should
692 // always be an end() iterator.
693 assert(use == MBB->end() && "No use marked in intrablock");
695 MachineBasicBlock::iterator walker = use;
697 while (walker != MBB->begin())
698 if (BlockDefs.count(walker)) {
703 // Once we've found it, extend its VNInfo to our instruction.
704 unsigned DefIndex = LIs->getInstructionIndex(walker);
705 DefIndex = LiveIntervals::getDefIndex(DefIndex);
706 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
708 ret = NewVNs[walker];
709 LI->addRange(LiveRange(DefIndex, EndIndex+1, ret));
710 } else if (!ContainsDefs && ContainsUses) {
711 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
713 // Search for the use in this block that precedes the instruction we care
714 // about, going to the fallback case if we don't find it.
716 if (use == MBB->begin())
719 MachineBasicBlock::iterator walker = use;
722 while (walker != MBB->begin())
723 if (BlockUses.count(walker)) {
729 // Must check begin() too.
731 if (BlockUses.count(walker))
737 unsigned UseIndex = LIs->getInstructionIndex(walker);
738 UseIndex = LiveIntervals::getUseIndex(UseIndex);
739 unsigned EndIndex = 0;
741 EndIndex = LIs->getInstructionIndex(use);
742 EndIndex = LiveIntervals::getUseIndex(EndIndex);
744 EndIndex = LIs->getMBBEndIdx(MBB);
746 // Now, recursively phi construct the VNInfo for the use we found,
747 // and then extend it to include the instruction we care about
748 ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
749 NewVNs, LiveOut, Phis, false, true);
751 LI->addRange(LiveRange(UseIndex, EndIndex+1, ret));
753 // FIXME: Need to set kills properly for inter-block stuff.
754 if (LI->isKill(ret, UseIndex)) LI->removeKill(ret, UseIndex);
756 LI->addKill(ret, EndIndex);
757 } else if (ContainsDefs && ContainsUses){
758 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
759 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
761 // This case is basically a merging of the two preceding case, with the
762 // special note that checking for defs must take precedence over checking
763 // for uses, because of two-address instructions.
765 if (use == MBB->begin())
768 MachineBasicBlock::iterator walker = use;
770 bool foundDef = false;
771 bool foundUse = false;
772 while (walker != MBB->begin())
773 if (BlockDefs.count(walker)) {
776 } else if (BlockUses.count(walker)) {
782 // Must check begin() too.
783 if (!foundDef && !foundUse) {
784 if (BlockDefs.count(walker))
786 else if (BlockUses.count(walker))
792 unsigned StartIndex = LIs->getInstructionIndex(walker);
793 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
794 LiveIntervals::getUseIndex(StartIndex);
795 unsigned EndIndex = 0;
797 EndIndex = LIs->getInstructionIndex(use);
798 EndIndex = LiveIntervals::getUseIndex(EndIndex);
800 EndIndex = LIs->getMBBEndIdx(MBB);
803 ret = NewVNs[walker];
805 ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
806 NewVNs, LiveOut, Phis, false, true);
808 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
810 if (foundUse && LI->isKill(ret, StartIndex))
811 LI->removeKill(ret, StartIndex);
813 LI->addKill(ret, EndIndex);
817 // Memoize results so we don't have to recompute them.
818 if (!intrablock) LiveOut[MBB] = ret;
820 if (!NewVNs.count(use))
828 /// ReconstructLiveInterval - Recompute a live interval from scratch.
829 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
830 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
832 // Clear the old ranges and valnos;
835 // Cache the uses and defs of the register
836 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
839 // Keep track of the new VNs we're creating.
840 DenseMap<MachineInstr*, VNInfo*> NewVNs;
841 SmallPtrSet<VNInfo*, 2> PhiVNs;
843 // Cache defs, and create a new VNInfo for each def.
844 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
845 DE = MRI->def_end(); DI != DE; ++DI) {
846 Defs[(*DI).getParent()].insert(&*DI);
848 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
849 DefIdx = LiveIntervals::getDefIndex(DefIdx);
851 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
853 // If the def is a move, set the copy field.
854 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
855 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
856 if (DstReg == LI->reg)
859 NewVNs[&*DI] = NewVN;
862 // Cache uses as a separate pass from actually processing them.
863 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
864 UE = MRI->use_end(); UI != UE; ++UI)
865 Uses[(*UI).getParent()].insert(&*UI);
867 // Now, actually process every use and use a phi construction algorithm
868 // to walk from it to its reaching definitions, building VNInfos along
870 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
871 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
872 SmallPtrSet<MachineInstr*, 4> Visited;
873 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
874 UE = MRI->use_end(); UI != UE; ++UI) {
875 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
876 Uses, NewVNs, LiveOut, Phis, true, true);
879 // Add ranges for dead defs
880 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
881 DE = MRI->def_end(); DI != DE; ++DI) {
882 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
883 DefIdx = LiveIntervals::getDefIndex(DefIdx);
885 if (LI->liveAt(DefIdx)) continue;
887 VNInfo* DeadVN = NewVNs[&*DI];
888 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
889 LI->addKill(DeadVN, DefIdx);
893 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
894 /// chain to find the new 'kills' and shrink wrap the live interval to the
895 /// new kill indices.
897 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
898 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
899 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
900 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
901 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
902 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
903 if (Visited.count(MBB))
906 // If live interval is live in another successor path, then we can't process
907 // this block. But we may able to do so after all the successors have been
909 if (MBB != BarrierMBB) {
910 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
911 SE = MBB->succ_end(); SI != SE; ++SI) {
912 MachineBasicBlock *SMBB = *SI;
915 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
922 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
923 UMII = Uses.find(MBB);
924 if (UMII != Uses.end()) {
925 // At least one use in this mbb, lets look for the kill.
926 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
927 UMII2 = UseMIs.find(MBB);
928 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
929 // Found a kill, shrink wrapping of this path ends here.
931 } else if (MBB == DefMBB) {
932 // There are no uses after the def.
933 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
934 if (UseMBBs.empty()) {
935 // The only use must be below barrier in the barrier block. It's safe to
937 LIs->RemoveMachineInstrFromMaps(DefMI);
938 DefMI->eraseFromParent();
939 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
941 } else if (MBB == BarrierMBB) {
942 // Remove entire live range from start of mbb to barrier.
943 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
944 LIs->getUseIndex(BarrierIdx)+1);
946 // Remove entire live range of the mbb out of the live interval.
947 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
951 // Reached the def mbb, stop traversing this path further.
954 // Traverse the pathes up the predecessor chains further.
955 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
956 PE = MBB->pred_end(); PI != PE; ++PI) {
957 MachineBasicBlock *Pred = *PI;
960 if (Pred == DefMBB && ValNo->hasPHIKill)
961 // Pred is the def bb and the def reaches other val#s, we must
962 // allow the value to be live out of the bb.
964 if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
966 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
967 Uses, UseMIs, UseMBBs);
974 void PreAllocSplitting::RepairLiveInterval(LiveInterval* CurrLI,
977 unsigned RestoreIdx) {
978 // Shrink wrap the live interval by walking up the CFG and find the
980 // Now let's find all the uses of the val#.
981 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
982 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
983 SmallPtrSet<MachineBasicBlock*, 4> Seen;
984 SmallVector<MachineBasicBlock*, 4> UseMBBs;
985 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
986 UE = MRI->use_end(); UI != UE; ++UI) {
987 MachineOperand &UseMO = UI.getOperand();
988 MachineInstr *UseMI = UseMO.getParent();
989 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
990 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
991 if (ULR->valno != ValNo)
993 MachineBasicBlock *UseMBB = UseMI->getParent();
994 // Remember which other mbb's use this val#.
995 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
996 UseMBBs.push_back(UseMBB);
997 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
998 UMII = Uses.find(UseMBB);
999 if (UMII != Uses.end()) {
1000 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
1001 UMII2 = UseMIs.find(UseMBB);
1002 UMII->second.push_back(&UseMO);
1003 UMII2->second.insert(UseMI);
1005 SmallVector<MachineOperand*, 4> Ops;
1006 Ops.push_back(&UseMO);
1007 Uses.insert(std::make_pair(UseMBB, Ops));
1008 SmallPtrSet<MachineInstr*, 4> MIs;
1010 UseMIs.insert(std::make_pair(UseMBB, MIs));
1014 // Walk up the predecessor chains.
1015 SmallPtrSet<MachineBasicBlock*, 8> Visited;
1016 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMI->getParent(), Visited,
1017 Uses, UseMIs, UseMBBs);
1019 // Remove live range from barrier to the restore. FIXME: Find a better
1020 // point to re-start the live interval.
1021 VNInfo* AfterValNo = UpdateRegisterInterval(ValNo,
1022 LIs->getUseIndex(BarrierIdx)+1,
1023 LIs->getDefIndex(RestoreIdx));
1025 // Attempt to renumber the new valno into a new vreg.
1026 RenumberValno(AfterValNo);
1029 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
1030 /// be allocated to a different register. This function creates a new vreg,
1031 /// copies the valno and its live ranges over to the new vreg's interval,
1032 /// removes them from the old interval, and rewrites all uses and defs of
1033 /// the original reg to the new vreg within those ranges.
1034 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
1035 SmallVector<VNInfo*, 4> Stack;
1036 SmallVector<VNInfo*, 4> VNsToCopy;
1037 Stack.push_back(VN);
1039 // Walk through and copy the valno we care about, and any other valnos
1040 // that are two-address redefinitions of the one we care about. These
1041 // will need to be rewritten as well. We also check for safety of the
1042 // renumbering here, by making sure that none of the valno involved has
1044 while (!Stack.empty()) {
1045 VNInfo* OldVN = Stack.back();
1048 // Bail out if we ever encounter a valno that has a PHI kill. We can't
1050 if (OldVN->hasPHIKill) return;
1052 VNsToCopy.push_back(OldVN);
1054 // Locate two-address redefinitions
1055 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
1056 KE = OldVN->kills.end(); KI != KE; ++KI) {
1057 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
1058 //if (!MI) continue;
1059 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
1060 if (DefIdx == ~0U) continue;
1061 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
1063 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
1064 Stack.push_back(NextVN);
1069 // Create the new vreg
1070 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
1072 // Create the new live interval
1073 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
1075 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
1076 VNsToCopy.end(); OI != OE; ++OI) {
1077 VNInfo* OldVN = *OI;
1079 // Copy the valno over
1080 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
1081 LIs->getVNInfoAllocator());
1082 NewLI.copyValNumInfo(NewVN, OldVN);
1083 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
1085 // Remove the valno from the old interval
1086 CurrLI->removeValNo(OldVN);
1089 // Rewrite defs and uses. This is done in two stages to avoid invalidating
1090 // the reg_iterator.
1091 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
1093 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1094 E = MRI->reg_end(); I != E; ++I) {
1095 MachineOperand& MO = I.getOperand();
1096 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
1098 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
1099 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
1100 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
1103 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
1104 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
1105 MachineInstr* Inst = I->first;
1106 unsigned OpIdx = I->second;
1107 MachineOperand& MO = Inst->getOperand(OpIdx);
1114 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
1115 MachineInstr* DefMI,
1116 MachineBasicBlock::iterator RestorePt,
1117 unsigned RestoreIdx,
1118 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1119 MachineBasicBlock& MBB = *RestorePt->getParent();
1121 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
1122 unsigned KillIdx = 0;
1123 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
1124 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
1126 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
1128 if (KillPt == DefMI->getParent()->end())
1131 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
1132 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
1134 ReconstructLiveInterval(CurrLI);
1135 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
1136 RematIdx = LiveIntervals::getDefIndex(RematIdx);
1137 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
1144 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
1145 const TargetRegisterClass* RC,
1146 MachineInstr* DefMI,
1147 MachineInstr* Barrier,
1148 MachineBasicBlock* MBB,
1150 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1151 MachineBasicBlock::iterator Pt = MBB->begin();
1153 // Go top down if RefsInMBB is empty.
1154 if (RefsInMBB.empty())
1157 MachineBasicBlock::iterator FoldPt = Barrier;
1158 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
1159 !RefsInMBB.count(FoldPt))
1162 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
1166 SmallVector<unsigned, 1> Ops;
1167 Ops.push_back(OpIdx);
1169 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1172 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
1173 if (I != IntervalSSMap.end()) {
1176 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
1180 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1184 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1185 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1188 IntervalSSMap[vreg] = SS;
1189 CurrSLI = &LSs->getOrCreateInterval(SS);
1190 if (CurrSLI->hasAtLeastOneValue())
1191 CurrSValNo = CurrSLI->getValNumInfo(0);
1193 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1199 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1200 /// so it would not cross the barrier that's being processed. Shrink wrap
1201 /// (minimize) the live interval to the last uses.
1202 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1205 // Find live range where current interval cross the barrier.
1206 LiveInterval::iterator LR =
1207 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1208 VNInfo *ValNo = LR->valno;
1210 if (ValNo->def == ~1U) {
1211 // Defined by a dead def? How can this be?
1212 assert(0 && "Val# is defined by a dead def?");
1216 MachineInstr *DefMI = (ValNo->def != ~0U)
1217 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1219 // If this would create a new join point, do not split.
1220 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1223 // Find all references in the barrier mbb.
1224 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1225 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1226 E = MRI->reg_end(); I != E; ++I) {
1227 MachineInstr *RefMI = &*I;
1228 if (RefMI->getParent() == BarrierMBB)
1229 RefsInMBB.insert(RefMI);
1232 // Find a point to restore the value after the barrier.
1233 unsigned RestoreIndex = 0;
1234 MachineBasicBlock::iterator RestorePt =
1235 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1236 if (RestorePt == BarrierMBB->end())
1239 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1240 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1241 RestoreIndex, RefsInMBB))
1244 // Add a spill either before the barrier or after the definition.
1245 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1246 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1247 unsigned SpillIndex = 0;
1248 MachineInstr *SpillMI = NULL;
1250 if (ValNo->def == ~0U) {
1251 // If it's defined by a phi, we must split just before the barrier.
1252 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1253 BarrierMBB, SS, RefsInMBB))) {
1254 SpillIndex = LIs->getInstructionIndex(SpillMI);
1256 MachineBasicBlock::iterator SpillPt =
1257 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1258 if (SpillPt == BarrierMBB->begin())
1259 return false; // No gap to insert spill.
1262 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1263 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1264 SpillMI = prior(SpillPt);
1265 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1267 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1268 RestoreIndex, SpillIndex, SS)) {
1269 // If it's already split, just restore the value. There is no need to spill
1272 return false; // Def is dead. Do nothing.
1274 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1275 BarrierMBB, SS, RefsInMBB))) {
1276 SpillIndex = LIs->getInstructionIndex(SpillMI);
1278 // Check if it's possible to insert a spill after the def MI.
1279 MachineBasicBlock::iterator SpillPt;
1280 if (DefMBB == BarrierMBB) {
1281 // Add spill after the def and the last use before the barrier.
1282 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1283 RefsInMBB, SpillIndex);
1284 if (SpillPt == DefMBB->begin())
1285 return false; // No gap to insert spill.
1287 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1288 if (SpillPt == DefMBB->end())
1289 return false; // No gap to insert spill.
1291 // Add spill. The store instruction kills the register if def is before
1292 // the barrier in the barrier block.
1293 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1294 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1295 DefMBB == BarrierMBB, SS, RC);
1296 SpillMI = prior(SpillPt);
1297 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1301 // Remember def instruction index to spill index mapping.
1302 if (DefMI && SpillMI)
1303 Def2SpillMap[ValNo->def] = SpillIndex;
1306 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1307 MachineInstr *LoadMI = prior(RestorePt);
1308 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1310 // Update spill stack slot live interval.
1311 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1312 LIs->getDefIndex(RestoreIndex));
1314 ReconstructLiveInterval(CurrLI);
1315 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1316 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1317 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1323 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1324 /// barrier that's being processed.
1326 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1327 SmallPtrSet<LiveInterval*, 8>& Split) {
1328 // First find all the virtual registers whose live intervals are intercepted
1329 // by the current barrier.
1330 SmallVector<LiveInterval*, 8> Intervals;
1331 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1332 if (TII->IgnoreRegisterClassBarriers(*RC))
1334 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1335 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1336 unsigned Reg = VRs[i];
1337 if (!LIs->hasInterval(Reg))
1339 LiveInterval *LI = &LIs->getInterval(Reg);
1340 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1341 // Virtual register live interval is intercepted by the barrier. We
1342 // should split and shrink wrap its interval if possible.
1343 Intervals.push_back(LI);
1347 // Process the affected live intervals.
1348 bool Change = false;
1349 while (!Intervals.empty()) {
1350 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1352 else if (NumSplits == 4)
1354 LiveInterval *LI = Intervals.back();
1355 Intervals.pop_back();
1356 bool result = SplitRegLiveInterval(LI);
1357 if (result) Split.insert(LI);
1364 unsigned PreAllocSplitting::getNumberOfSpills(
1365 SmallPtrSet<MachineInstr*, 4>& MIs,
1366 unsigned Reg, int FrameIndex) {
1367 unsigned Spills = 0;
1368 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1370 int StoreFrameIndex;
1371 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1372 if (StoreVReg == Reg && StoreFrameIndex == FrameIndex)
1379 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1380 /// split, and see if any of the spills are unnecessary. If so, remove them.
1381 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1382 bool changed = false;
1384 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1385 LE = split.end(); LI != LE; ++LI) {
1386 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1388 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1389 UE = MRI->use_end(); UI != UE; ++UI) {
1390 unsigned index = LIs->getInstructionIndex(&*UI);
1391 index = LiveIntervals::getUseIndex(index);
1393 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1394 VNUseCount[LR->valno].insert(&*UI);
1397 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1398 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1399 VNInfo* CurrVN = *VI;
1400 if (CurrVN->hasPHIKill) continue;
1402 unsigned DefIdx = CurrVN->def;
1403 if (DefIdx == ~0U || DefIdx == ~1U) continue;
1405 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1407 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1409 if (VNUseCount[CurrVN].size() == 0) {
1410 LIs->RemoveMachineInstrFromMaps(DefMI);
1411 (*LI)->removeValNo(CurrVN);
1412 DefMI->eraseFromParent();
1418 unsigned SpillCount = getNumberOfSpills(VNUseCount[CurrVN],
1419 (*LI)->reg, FrameIndex);
1420 if (SpillCount != VNUseCount[CurrVN].size()) continue;
1422 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1423 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1425 LIs->RemoveMachineInstrFromMaps(*UI);
1426 (*UI)->eraseFromParent();
1429 LIs->RemoveMachineInstrFromMaps(DefMI);
1430 (*LI)->removeValNo(CurrVN);
1431 DefMI->eraseFromParent();
1440 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1441 MachineBasicBlock* DefMBB,
1442 MachineBasicBlock* BarrierMBB) {
1443 if (DefMBB == BarrierMBB)
1446 if (LR->valno->hasPHIKill)
1449 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1450 if (LR->end < MBBEnd)
1453 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1454 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1457 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1458 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1459 typedef std::pair<MachineBasicBlock*,
1460 MachineBasicBlock::succ_iterator> ItPair;
1461 SmallVector<ItPair, 4> Stack;
1462 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1464 while (!Stack.empty()) {
1465 ItPair P = Stack.back();
1468 MachineBasicBlock* PredMBB = P.first;
1469 MachineBasicBlock::succ_iterator S = P.second;
1471 if (S == PredMBB->succ_end())
1473 else if (Visited.count(*S)) {
1474 Stack.push_back(std::make_pair(PredMBB, ++S));
1477 Stack.push_back(std::make_pair(PredMBB, S+1));
1479 MachineBasicBlock* MBB = *S;
1480 Visited.insert(MBB);
1482 if (MBB == BarrierMBB)
1485 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1486 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1487 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1489 if (MDTN == DefMDTN)
1491 else if (MDTN == BarrierMDTN)
1493 MDTN = MDTN->getIDom();
1496 MBBEnd = LIs->getMBBEndIdx(MBB);
1497 if (LR->end > MBBEnd)
1498 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1505 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1507 TM = &MF.getTarget();
1508 TII = TM->getInstrInfo();
1509 MFI = MF.getFrameInfo();
1510 MRI = &MF.getRegInfo();
1511 LIs = &getAnalysis<LiveIntervals>();
1512 LSs = &getAnalysis<LiveStacks>();
1514 bool MadeChange = false;
1516 // Make sure blocks are numbered in order.
1517 MF.RenumberBlocks();
1519 MachineBasicBlock *Entry = MF.begin();
1520 SmallPtrSet<MachineBasicBlock*,16> Visited;
1522 SmallPtrSet<LiveInterval*, 8> Split;
1524 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1525 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1528 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1529 E = BarrierMBB->end(); I != E; ++I) {
1531 const TargetRegisterClass **BarrierRCs =
1532 Barrier->getDesc().getRegClassBarriers();
1535 BarrierIdx = LIs->getInstructionIndex(Barrier);
1536 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1540 MadeChange |= removeDeadSpills(Split);