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");
47 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
48 MachineFunction *CurrMF;
49 const TargetMachine *TM;
50 const TargetInstrInfo *TII;
51 MachineFrameInfo *MFI;
52 MachineRegisterInfo *MRI;
56 // Barrier - Current barrier being processed.
57 MachineInstr *Barrier;
59 // BarrierMBB - Basic block where the barrier resides in.
60 MachineBasicBlock *BarrierMBB;
62 // Barrier - Current barrier index.
65 // CurrLI - Current live interval being split.
68 // CurrSLI - Current stack slot live interval.
69 LiveInterval *CurrSLI;
71 // CurrSValNo - Current val# for the stack slot live interval.
74 // IntervalSSMap - A map from live interval to spill slots.
75 DenseMap<unsigned, int> IntervalSSMap;
77 // Def2SpillMap - A map from a def instruction index to spill index.
78 DenseMap<unsigned, unsigned> Def2SpillMap;
82 PreAllocSplitting() : MachineFunctionPass(&ID) {}
84 virtual bool runOnMachineFunction(MachineFunction &MF);
86 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequired<LiveIntervals>();
88 AU.addPreserved<LiveIntervals>();
89 AU.addRequired<LiveStacks>();
90 AU.addPreserved<LiveStacks>();
91 AU.addPreserved<RegisterCoalescer>();
93 AU.addPreservedID(StrongPHIEliminationID);
95 AU.addPreservedID(PHIEliminationID);
96 AU.addRequired<MachineDominatorTree>();
97 AU.addRequired<MachineLoopInfo>();
98 AU.addPreserved<MachineDominatorTree>();
99 AU.addPreserved<MachineLoopInfo>();
100 MachineFunctionPass::getAnalysisUsage(AU);
103 virtual void releaseMemory() {
104 IntervalSSMap.clear();
105 Def2SpillMap.clear();
108 virtual const char *getPassName() const {
109 return "Pre-Register Allocaton Live Interval Splitting";
112 /// print - Implement the dump method.
113 virtual void print(std::ostream &O, const Module* M = 0) const {
117 void print(std::ostream *O, const Module* M = 0) const {
122 MachineBasicBlock::iterator
123 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
126 MachineBasicBlock::iterator
127 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
128 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
130 MachineBasicBlock::iterator
131 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
132 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
134 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
136 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
137 unsigned&, int&) const;
139 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
141 VNInfo* UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
143 bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
144 SmallVector<MachineOperand*, 4>&,
145 SmallPtrSet<MachineInstr*, 4>&);
147 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
148 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
149 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
150 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
151 SmallVector<MachineBasicBlock*, 4>&);
153 bool SplitRegLiveInterval(LiveInterval*);
155 bool SplitRegLiveIntervals(const TargetRegisterClass **);
157 void RepairLiveInterval(LiveInterval* CurrLI, VNInfo* ValNo,
158 MachineInstr* DefMI, unsigned RestoreIdx);
160 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
161 MachineBasicBlock* BarrierMBB);
162 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
164 MachineBasicBlock::iterator RestorePt,
166 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
167 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
169 MachineInstr* Barrier,
170 MachineBasicBlock* MBB,
172 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
173 void RenumberValno(VNInfo* VN);
174 void ReconstructLiveInterval(LiveInterval* LI);
175 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator use,
177 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
178 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
179 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
180 DenseMap<MachineBasicBlock*, VNInfo*>& Visited,
181 bool toplevel = false);
183 } // end anonymous namespace
185 char PreAllocSplitting::ID = 0;
187 static RegisterPass<PreAllocSplitting>
188 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
190 const PassInfo *const llvm::PreAllocSplittingID = &X;
193 /// findNextEmptySlot - Find a gap after the given machine instruction in the
194 /// instruction index map. If there isn't one, return end().
195 MachineBasicBlock::iterator
196 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
197 unsigned &SpotIndex) {
198 MachineBasicBlock::iterator MII = MI;
199 if (++MII != MBB->end()) {
200 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
209 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
210 /// for spilling the current live interval. The index must be before any
211 /// defs and uses of the live interval register in the mbb. Return begin() if
213 MachineBasicBlock::iterator
214 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
216 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
217 unsigned &SpillIndex) {
218 MachineBasicBlock::iterator Pt = MBB->begin();
220 // Go top down if RefsInMBB is empty.
221 if (RefsInMBB.empty() && !DefMI) {
222 MachineBasicBlock::iterator MII = MBB->begin();
223 MachineBasicBlock::iterator EndPt = MI;
226 unsigned Index = LIs->getInstructionIndex(MII);
227 unsigned Gap = LIs->findGapBeforeInstr(Index);
233 } while (MII != EndPt);
235 MachineBasicBlock::iterator MII = MI;
236 MachineBasicBlock::iterator EndPt = DefMI
237 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
238 while (MII != EndPt && !RefsInMBB.count(MII)) {
239 unsigned Index = LIs->getInstructionIndex(MII);
240 if (LIs->hasGapBeforeInstr(Index)) {
242 SpillIndex = LIs->findGapBeforeInstr(Index, true);
251 /// findRestorePoint - Find a gap in the instruction index map that's suitable
252 /// for restoring the current live interval value. The index must be before any
253 /// uses of the live interval register in the mbb. Return end() if none is
255 MachineBasicBlock::iterator
256 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
258 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
259 unsigned &RestoreIndex) {
260 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
261 // begin index accordingly.
262 MachineBasicBlock::iterator Pt = MBB->end();
263 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
265 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
266 // the last index in the live range.
267 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
268 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
269 MachineBasicBlock::iterator EndPt = MI;
272 unsigned Index = LIs->getInstructionIndex(MII);
273 unsigned Gap = LIs->findGapBeforeInstr(Index);
280 } while (MII != EndPt);
282 MachineBasicBlock::iterator MII = MI;
284 // FIXME: Limit the number of instructions to examine to reduce
286 while (MII != MBB->end()) {
287 unsigned Index = LIs->getInstructionIndex(MII);
290 unsigned Gap = LIs->findGapBeforeInstr(Index);
295 if (RefsInMBB.count(MII))
304 /// CreateSpillStackSlot - Create a stack slot for the live interval being
305 /// split. If the live interval was previously split, just reuse the same
307 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
308 const TargetRegisterClass *RC) {
310 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
311 if (I != IntervalSSMap.end()) {
314 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
315 IntervalSSMap[Reg] = SS;
318 // Create live interval for stack slot.
319 CurrSLI = &LSs->getOrCreateInterval(SS);
320 if (CurrSLI->hasAtLeastOneValue())
321 CurrSValNo = CurrSLI->getValNumInfo(0);
323 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
327 /// IsAvailableInStack - Return true if register is available in a split stack
328 /// slot at the specified index.
330 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
331 unsigned Reg, unsigned DefIndex,
332 unsigned RestoreIndex, unsigned &SpillIndex,
337 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
338 if (I == IntervalSSMap.end())
340 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
341 if (II == Def2SpillMap.end())
344 // If last spill of def is in the same mbb as barrier mbb (where restore will
345 // be), make sure it's not below the intended restore index.
346 // FIXME: Undo the previous spill?
347 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
348 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
352 SpillIndex = II->second;
356 /// UpdateSpillSlotInterval - Given the specified val# of the register live
357 /// interval being split, and the spill and restore indicies, update the live
358 /// interval of the spill stack slot.
360 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
361 unsigned RestoreIndex) {
362 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
363 "Expect restore in the barrier mbb");
365 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
366 if (MBB == BarrierMBB) {
367 // Intra-block spill + restore. We are done.
368 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
369 CurrSLI->addRange(SLR);
373 SmallPtrSet<MachineBasicBlock*, 4> Processed;
374 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
375 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
376 CurrSLI->addRange(SLR);
377 Processed.insert(MBB);
379 // Start from the spill mbb, figure out the extend of the spill slot's
381 SmallVector<MachineBasicBlock*, 4> WorkList;
382 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
383 if (LR->end > EndIdx)
384 // If live range extend beyond end of mbb, add successors to work list.
385 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
386 SE = MBB->succ_end(); SI != SE; ++SI)
387 WorkList.push_back(*SI);
389 while (!WorkList.empty()) {
390 MachineBasicBlock *MBB = WorkList.back();
392 if (Processed.count(MBB))
394 unsigned Idx = LIs->getMBBStartIdx(MBB);
395 LR = CurrLI->getLiveRangeContaining(Idx);
396 if (LR && LR->valno == ValNo) {
397 EndIdx = LIs->getMBBEndIdx(MBB);
398 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
399 // Spill slot live interval stops at the restore.
400 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
401 CurrSLI->addRange(SLR);
402 } else if (LR->end > EndIdx) {
403 // Live range extends beyond end of mbb, process successors.
404 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
405 CurrSLI->addRange(SLR);
406 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
407 SE = MBB->succ_end(); SI != SE; ++SI)
408 WorkList.push_back(*SI);
410 LiveRange SLR(Idx, LR->end, CurrSValNo);
411 CurrSLI->addRange(SLR);
413 Processed.insert(MBB);
418 /// UpdateRegisterInterval - Given the specified val# of the current live
419 /// interval is being split, and the spill and restore indices, update the live
420 /// interval accordingly.
422 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
423 unsigned RestoreIndex) {
424 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
425 "Expect restore in the barrier mbb");
427 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
428 SmallVector<std::pair<unsigned,unsigned>, 4> After;
429 SmallVector<unsigned, 4> BeforeKills;
430 SmallVector<unsigned, 4> AfterKills;
431 SmallPtrSet<const LiveRange*, 4> Processed;
433 // First, let's figure out which parts of the live interval is now defined
434 // by the restore, which are defined by the original definition.
435 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
436 After.push_back(std::make_pair(RestoreIndex, LR->end));
437 if (CurrLI->isKill(ValNo, LR->end))
438 AfterKills.push_back(LR->end);
440 assert(LR->contains(SpillIndex));
441 if (SpillIndex > LR->start) {
442 Before.push_back(std::make_pair(LR->start, SpillIndex));
443 BeforeKills.push_back(SpillIndex);
445 Processed.insert(LR);
447 // Start from the restore mbb, figure out what part of the live interval
448 // are defined by the restore.
449 SmallVector<MachineBasicBlock*, 4> WorkList;
450 MachineBasicBlock *MBB = BarrierMBB;
451 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
452 SE = MBB->succ_end(); SI != SE; ++SI)
453 WorkList.push_back(*SI);
455 SmallPtrSet<MachineBasicBlock*, 4> ProcessedBlocks;
456 ProcessedBlocks.insert(MBB);
458 while (!WorkList.empty()) {
459 MBB = WorkList.back();
461 unsigned Idx = LIs->getMBBStartIdx(MBB);
462 LR = CurrLI->getLiveRangeContaining(Idx);
463 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
464 After.push_back(std::make_pair(LR->start, LR->end));
465 if (CurrLI->isKill(ValNo, LR->end))
466 AfterKills.push_back(LR->end);
467 Idx = LIs->getMBBEndIdx(MBB);
469 // Live range extend beyond at least one mbb. Let's see what other
471 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
473 Processed.insert(LR);
476 ProcessedBlocks.insert(MBB);
478 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
479 SE = MBB->succ_end(); SI != SE; ++SI)
480 if (!ProcessedBlocks.count(*SI))
481 WorkList.push_back(*SI);
484 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
487 if (LR->valno == ValNo && !Processed.count(LR)) {
488 Before.push_back(std::make_pair(LR->start, LR->end));
489 if (CurrLI->isKill(ValNo, LR->end))
490 BeforeKills.push_back(LR->end);
494 // Now create new val#s to represent the live ranges defined by the old def
495 // those defined by the restore.
496 unsigned AfterDef = ValNo->def;
497 MachineInstr *AfterCopy = ValNo->copy;
498 bool HasPHIKill = ValNo->hasPHIKill;
499 CurrLI->removeValNo(ValNo);
500 VNInfo *BValNo = (Before.empty())
502 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
504 CurrLI->addKills(BValNo, BeforeKills);
506 VNInfo *AValNo = (After.empty())
508 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
510 AValNo->hasPHIKill = HasPHIKill;
511 CurrLI->addKills(AValNo, AfterKills);
514 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
515 unsigned Start = Before[i].first;
516 unsigned End = Before[i].second;
517 CurrLI->addRange(LiveRange(Start, End, BValNo));
519 for (unsigned i = 0, e = After.size(); i != e; ++i) {
520 unsigned Start = After[i].first;
521 unsigned End = After[i].second;
522 CurrLI->addRange(LiveRange(Start, End, AValNo));
528 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
529 /// given block, shrink wrap the live interval to the last use (i.e. remove
530 /// from last use to the end of the mbb). In case mbb is the where the barrier
531 /// is, remove from the last use to the barrier.
533 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
534 SmallVector<MachineOperand*, 4> &Uses,
535 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
536 MachineOperand *LastMO = 0;
537 MachineInstr *LastMI = 0;
538 if (MBB != BarrierMBB && Uses.size() == 1) {
539 // Single use, no need to traverse the block. We can't assume this for the
540 // barrier bb though since the use is probably below the barrier.
542 LastMI = LastMO->getParent();
544 MachineBasicBlock::iterator MEE = MBB->begin();
545 MachineBasicBlock::iterator MII;
546 if (MBB == BarrierMBB)
552 MachineInstr *UseMI = &*MII;
553 if (!UseMIs.count(UseMI))
555 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
556 MachineOperand &MO = UseMI->getOperand(i);
557 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
567 // Cut off live range from last use (or beginning of the mbb if there
568 // are no uses in it) to the end of the mbb.
569 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
571 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
572 assert(!LastMO->isKill() && "Last use already terminates the interval?");
575 assert(MBB == BarrierMBB);
576 RangeStart = LIs->getMBBStartIdx(MBB);
578 if (MBB == BarrierMBB)
579 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
580 CurrLI->removeRange(RangeStart, RangeEnd);
582 CurrLI->addKill(ValNo, RangeStart);
584 // Return true if the last use becomes a new kill.
588 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
589 /// construction algorithm to compute the ranges and valnos for an interval.
590 VNInfo* PreAllocSplitting::PerformPHIConstruction(
591 MachineBasicBlock::iterator use,
593 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
594 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
595 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
596 DenseMap<MachineBasicBlock*, VNInfo*>& Visited,
598 // Return memoized result if it's available.
599 if (Visited.count(use->getParent()))
600 return Visited[use->getParent()];
602 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
604 // Check if our block contains any uses or defs.
605 bool ContainsDefs = Defs.count(use->getParent());
606 bool ContainsUses = Uses.count(use->getParent());
610 // Enumerate the cases of use/def contaning blocks.
611 if (!ContainsDefs && !ContainsUses) {
613 // NOTE: Because this is the fallback case from other cases, we do NOT
614 // assume that we are not at toplevel here.
616 // If there are no uses or defs between our starting point and the beginning
617 // of the block, then recursive perform phi construction on our predecessors
618 MachineBasicBlock* MBB = use->getParent();
619 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
620 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
621 PE = MBB->pred_end(); PI != PE; ++PI) {
622 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), LI, Defs, Uses,
623 NewVNs, Visited, false);
624 IncomingVNs[*PI] = Incoming;
627 // If only one VNInfo came back from our predecessors, just use that one...
628 if (IncomingVNs.size() == 1) {
629 ret = IncomingVNs.begin()->second;
630 unsigned StartIndex = LIs->getMBBStartIdx(use->getParent());
631 unsigned EndIndex = 0;
633 EndIndex = LIs->getInstructionIndex(use);
634 EndIndex = LiveIntervals::getUseIndex(EndIndex);
636 EndIndex = LIs->getMBBEndIdx(use->getParent());
638 LI->addRange(LiveRange(StartIndex, EndIndex, ret));
640 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
641 // VNInfo to represent the joined value.
642 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
643 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
644 I->second->hasPHIKill = true;
645 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
646 LI->addKill(I->second, KillIndex);
649 unsigned StartIndex = LIs->getMBBStartIdx(use->getParent());
650 unsigned EndIndex = 0;
652 EndIndex = LIs->getInstructionIndex(use);
653 EndIndex = LiveIntervals::getUseIndex(EndIndex);
655 EndIndex = LIs->getMBBEndIdx(use->getParent());
656 ret = LI->getNextValue(StartIndex, /*FIXME*/ 0,
657 LIs->getVNInfoAllocator());
658 LI->addRange(LiveRange(StartIndex, EndIndex, ret));
660 } else if (ContainsDefs && !ContainsUses) {
661 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[use->getParent()];
663 // Search for the def in this block. If we don't find it before the
664 // instruction we care about, go to the fallback case. Note that that
665 // should never happen: this cannot be a toplevel block, so use should
666 // always be an end() iterator.
667 assert(use == use->getParent()->end() && "No use marked in toplevel block");
669 MachineBasicBlock::iterator walker = use;
671 while (walker != use->getParent()->begin())
672 if (BlockDefs.count(walker)) {
677 // Once we've found it, extend its VNInfo to our instruction.
678 unsigned DefIndex = LIs->getInstructionIndex(walker);
679 DefIndex = LiveIntervals::getDefIndex(DefIndex);
680 unsigned EndIndex = LIs->getMBBEndIdx(use->getParent());
682 ret = NewVNs[walker];
683 LI->addRange(LiveRange(DefIndex, EndIndex, ret));
684 } else if (!ContainsDefs && ContainsUses) {
685 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[use->getParent()];
687 // Search for the use in this block that precedes the instruction we care
688 // about, going to the fallback case if we don't find it.
690 if (use == use->getParent()->begin())
693 MachineBasicBlock::iterator walker = use;
696 while (walker != use->getParent()->begin())
697 if (BlockUses.count(walker)) {
703 // Must check begin() too.
705 if (BlockUses.count(walker))
710 unsigned UseIndex = LIs->getInstructionIndex(walker);
711 UseIndex = LiveIntervals::getUseIndex(UseIndex);
712 unsigned EndIndex = 0;
714 EndIndex = LIs->getInstructionIndex(walker);
715 EndIndex = LiveIntervals::getUseIndex(EndIndex);
717 EndIndex = LIs->getMBBEndIdx(use->getParent());
719 // Now, recursively phi construct the VNInfo for the use we found,
720 // and then extend it to include the instruction we care about
721 ret = PerformPHIConstruction(walker, LI, Defs, Uses,
722 NewVNs, Visited, false);
724 // FIXME: Need to set kills properly for inter-block stuff.
725 if (LI->isKill(ret, UseIndex)) LI->removeKill(ret, UseIndex);
727 LI->addKill(ret, EndIndex);
729 LI->addRange(LiveRange(UseIndex, EndIndex, ret));
730 } else if (ContainsDefs && ContainsUses){
731 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[use->getParent()];
732 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[use->getParent()];
734 // This case is basically a merging of the two preceding case, with the
735 // special note that checking for defs must take precedence over checking
736 // for uses, because of two-address instructions.
738 if (use == use->getParent()->begin())
741 MachineBasicBlock::iterator walker = use;
743 bool foundDef = false;
744 bool foundUse = false;
745 while (walker != use->getParent()->begin())
746 if (BlockDefs.count(walker)) {
749 } else if (BlockUses.count(walker)) {
755 // Must check begin() too.
756 if (!foundDef && !foundUse)
757 if (BlockDefs.count(walker))
759 else if (BlockUses.count(walker))
764 unsigned StartIndex = LIs->getInstructionIndex(walker);
765 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
766 LiveIntervals::getUseIndex(StartIndex);
767 unsigned EndIndex = 0;
769 EndIndex = LIs->getInstructionIndex(walker);
770 EndIndex = LiveIntervals::getUseIndex(EndIndex);
772 EndIndex = LIs->getMBBEndIdx(use->getParent());
775 ret = NewVNs[walker];
777 ret = PerformPHIConstruction(walker, LI, Defs, Uses,
778 NewVNs, Visited, false);
780 if (foundUse && LI->isKill(ret, StartIndex))
781 LI->removeKill(ret, StartIndex);
783 LI->addKill(ret, EndIndex);
786 LI->addRange(LiveRange(StartIndex, EndIndex, ret));
789 // Memoize results so we don't have to recompute them.
790 if (!toplevel) Visited[use->getParent()] = ret;
795 /// ReconstructLiveInterval - Recompute a live interval from scratch.
796 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
797 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
799 // Clear the old ranges and valnos;
802 // Cache the uses and defs of the register
803 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
806 // Keep track of the new VNs we're creating.
807 DenseMap<MachineInstr*, VNInfo*> NewVNs;
808 SmallPtrSet<VNInfo*, 2> PhiVNs;
810 // Cache defs, and create a new VNInfo for each def.
811 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
812 DE = MRI->def_end(); DI != DE; ++DI) {
813 Defs[(*DI).getParent()].insert(&*DI);
815 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
816 DefIdx = LiveIntervals::getDefIndex(DefIdx);
818 VNInfo* NewVN = LI->getNextValue(DefIdx, /*FIXME*/ 0, Alloc);
819 NewVNs[&*DI] = NewVN;
822 // Cache uses as a separate pass from actually processing them.
823 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
824 UE = MRI->use_end(); UI != UE; ++UI)
825 Uses[(*UI).getParent()].insert(&*UI);
827 // Now, actually process every use and use a phi construction algorithm
828 // to walk from it to its reaching definitions, building VNInfos along
830 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
831 UE = MRI->use_end(); UI != UE; ++UI) {
832 DenseMap<MachineBasicBlock*, VNInfo*> Visited;
833 PerformPHIConstruction(&*UI, LI, Defs, Uses, NewVNs, Visited, true);
836 // Add ranges for dead defs
837 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
838 DE = MRI->def_end(); DI != DE; ++DI) {
839 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
840 DefIdx = LiveIntervals::getDefIndex(DefIdx);
841 unsigned UseIdx = LiveIntervals::getUseIndex(DefIdx);
843 if (LI->liveAt(DefIdx)) continue;
845 VNInfo* DeadVN = NewVNs[&*DI];
846 LI->addRange(LiveRange(DefIdx, UseIdx, DeadVN));
847 LI->addKill(DeadVN, DefIdx);
851 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
852 /// chain to find the new 'kills' and shrink wrap the live interval to the
853 /// new kill indices.
855 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
856 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
857 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
858 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
859 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
860 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
861 if (Visited.count(MBB))
864 // If live interval is live in another successor path, then we can't process
865 // this block. But we may able to do so after all the successors have been
867 if (MBB != BarrierMBB) {
868 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
869 SE = MBB->succ_end(); SI != SE; ++SI) {
870 MachineBasicBlock *SMBB = *SI;
873 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
880 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
881 UMII = Uses.find(MBB);
882 if (UMII != Uses.end()) {
883 // At least one use in this mbb, lets look for the kill.
884 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
885 UMII2 = UseMIs.find(MBB);
886 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
887 // Found a kill, shrink wrapping of this path ends here.
889 } else if (MBB == DefMBB) {
890 // There are no uses after the def.
891 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
892 if (UseMBBs.empty()) {
893 // The only use must be below barrier in the barrier block. It's safe to
895 LIs->RemoveMachineInstrFromMaps(DefMI);
896 DefMI->eraseFromParent();
897 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
899 } else if (MBB == BarrierMBB) {
900 // Remove entire live range from start of mbb to barrier.
901 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
902 LIs->getUseIndex(BarrierIdx)+1);
904 // Remove entire live range of the mbb out of the live interval.
905 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
909 // Reached the def mbb, stop traversing this path further.
912 // Traverse the pathes up the predecessor chains further.
913 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
914 PE = MBB->pred_end(); PI != PE; ++PI) {
915 MachineBasicBlock *Pred = *PI;
918 if (Pred == DefMBB && ValNo->hasPHIKill)
919 // Pred is the def bb and the def reaches other val#s, we must
920 // allow the value to be live out of the bb.
922 if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
924 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
925 Uses, UseMIs, UseMBBs);
932 void PreAllocSplitting::RepairLiveInterval(LiveInterval* CurrLI,
935 unsigned RestoreIdx) {
936 // Shrink wrap the live interval by walking up the CFG and find the
938 // Now let's find all the uses of the val#.
939 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
940 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
941 SmallPtrSet<MachineBasicBlock*, 4> Seen;
942 SmallVector<MachineBasicBlock*, 4> UseMBBs;
943 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
944 UE = MRI->use_end(); UI != UE; ++UI) {
945 MachineOperand &UseMO = UI.getOperand();
946 MachineInstr *UseMI = UseMO.getParent();
947 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
948 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
949 if (ULR->valno != ValNo)
951 MachineBasicBlock *UseMBB = UseMI->getParent();
952 // Remember which other mbb's use this val#.
953 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
954 UseMBBs.push_back(UseMBB);
955 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
956 UMII = Uses.find(UseMBB);
957 if (UMII != Uses.end()) {
958 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
959 UMII2 = UseMIs.find(UseMBB);
960 UMII->second.push_back(&UseMO);
961 UMII2->second.insert(UseMI);
963 SmallVector<MachineOperand*, 4> Ops;
964 Ops.push_back(&UseMO);
965 Uses.insert(std::make_pair(UseMBB, Ops));
966 SmallPtrSet<MachineInstr*, 4> MIs;
968 UseMIs.insert(std::make_pair(UseMBB, MIs));
972 // Walk up the predecessor chains.
973 SmallPtrSet<MachineBasicBlock*, 8> Visited;
974 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMI->getParent(), Visited,
975 Uses, UseMIs, UseMBBs);
977 // Remove live range from barrier to the restore. FIXME: Find a better
978 // point to re-start the live interval.
979 VNInfo* AfterValNo = UpdateRegisterInterval(ValNo,
980 LIs->getUseIndex(BarrierIdx)+1,
981 LIs->getDefIndex(RestoreIdx));
983 // Attempt to renumber the new valno into a new vreg.
984 RenumberValno(AfterValNo);
987 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
988 /// be allocated to a different register. This function creates a new vreg,
989 /// copies the valno and its live ranges over to the new vreg's interval,
990 /// removes them from the old interval, and rewrites all uses and defs of
991 /// the original reg to the new vreg within those ranges.
992 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
993 SmallVector<VNInfo*, 4> Stack;
994 SmallVector<VNInfo*, 4> VNsToCopy;
997 // Walk through and copy the valno we care about, and any other valnos
998 // that are two-address redefinitions of the one we care about. These
999 // will need to be rewritten as well. We also check for safety of the
1000 // renumbering here, by making sure that none of the valno involved has
1002 while (!Stack.empty()) {
1003 VNInfo* OldVN = Stack.back();
1006 // Bail out if we ever encounter a valno that has a PHI kill. We can't
1008 if (OldVN->hasPHIKill) return;
1010 VNsToCopy.push_back(OldVN);
1012 // Locate two-address redefinitions
1013 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
1014 KE = OldVN->kills.end(); KI != KE; ++KI) {
1015 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
1016 //if (!MI) continue;
1017 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
1018 if (DefIdx == ~0U) continue;
1019 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
1021 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
1022 Stack.push_back(NextVN);
1027 // Create the new vreg
1028 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
1030 // Create the new live interval
1031 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
1033 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
1034 VNsToCopy.end(); OI != OE; ++OI) {
1035 VNInfo* OldVN = *OI;
1037 // Copy the valno over
1038 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
1039 LIs->getVNInfoAllocator());
1040 NewLI.copyValNumInfo(NewVN, OldVN);
1041 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
1043 // Remove the valno from the old interval
1044 CurrLI->removeValNo(OldVN);
1047 // Rewrite defs and uses. This is done in two stages to avoid invalidating
1048 // the reg_iterator.
1049 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
1051 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1052 E = MRI->reg_end(); I != E; ++I) {
1053 MachineOperand& MO = I.getOperand();
1054 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
1056 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
1057 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
1058 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
1061 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
1062 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
1063 MachineInstr* Inst = I->first;
1064 unsigned OpIdx = I->second;
1065 MachineOperand& MO = Inst->getOperand(OpIdx);
1072 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
1073 MachineInstr* DefMI,
1074 MachineBasicBlock::iterator RestorePt,
1075 unsigned RestoreIdx,
1076 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1077 MachineBasicBlock& MBB = *RestorePt->getParent();
1079 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
1080 unsigned KillIdx = 0;
1081 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
1082 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
1084 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
1086 if (KillPt == DefMI->getParent()->end())
1089 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
1090 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
1092 if (KillPt->getParent() == BarrierMBB) {
1093 UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
1094 LIs->getDefIndex(RestoreIdx));
1101 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIdx);
1108 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
1109 const TargetRegisterClass* RC,
1110 MachineInstr* DefMI,
1111 MachineInstr* Barrier,
1112 MachineBasicBlock* MBB,
1114 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1115 MachineBasicBlock::iterator Pt = MBB->begin();
1117 // Go top down if RefsInMBB is empty.
1118 if (RefsInMBB.empty())
1121 MachineBasicBlock::iterator FoldPt = Barrier;
1122 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
1123 !RefsInMBB.count(FoldPt))
1126 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
1130 SmallVector<unsigned, 1> Ops;
1131 Ops.push_back(OpIdx);
1133 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1136 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
1137 if (I != IntervalSSMap.end()) {
1140 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
1144 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1148 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1149 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1152 IntervalSSMap[vreg] = SS;
1153 CurrSLI = &LSs->getOrCreateInterval(SS);
1154 if (CurrSLI->hasAtLeastOneValue())
1155 CurrSValNo = CurrSLI->getValNumInfo(0);
1157 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1163 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1164 /// so it would not cross the barrier that's being processed. Shrink wrap
1165 /// (minimize) the live interval to the last uses.
1166 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1169 // Find live range where current interval cross the barrier.
1170 LiveInterval::iterator LR =
1171 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1172 VNInfo *ValNo = LR->valno;
1174 if (ValNo->def == ~1U) {
1175 // Defined by a dead def? How can this be?
1176 assert(0 && "Val# is defined by a dead def?");
1180 MachineInstr *DefMI = (ValNo->def != ~0U)
1181 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1183 // If this would create a new join point, do not split.
1184 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1187 // Find all references in the barrier mbb.
1188 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1189 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1190 E = MRI->reg_end(); I != E; ++I) {
1191 MachineInstr *RefMI = &*I;
1192 if (RefMI->getParent() == BarrierMBB)
1193 RefsInMBB.insert(RefMI);
1196 // Find a point to restore the value after the barrier.
1197 unsigned RestoreIndex;
1198 MachineBasicBlock::iterator RestorePt =
1199 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1200 if (RestorePt == BarrierMBB->end())
1203 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1204 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1205 RestoreIndex, RefsInMBB))
1208 // Add a spill either before the barrier or after the definition.
1209 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1210 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1211 unsigned SpillIndex = 0;
1212 MachineInstr *SpillMI = NULL;
1214 if (ValNo->def == ~0U) {
1215 // If it's defined by a phi, we must split just before the barrier.
1216 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1217 BarrierMBB, SS, RefsInMBB))) {
1218 SpillIndex = LIs->getInstructionIndex(SpillMI);
1220 MachineBasicBlock::iterator SpillPt =
1221 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1222 if (SpillPt == BarrierMBB->begin())
1223 return false; // No gap to insert spill.
1226 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1227 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1228 SpillMI = prior(SpillPt);
1229 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1231 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1232 RestoreIndex, SpillIndex, SS)) {
1233 // If it's already split, just restore the value. There is no need to spill
1236 return false; // Def is dead. Do nothing.
1238 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1239 BarrierMBB, SS, RefsInMBB))) {
1240 SpillIndex = LIs->getInstructionIndex(SpillMI);
1242 // Check if it's possible to insert a spill after the def MI.
1243 MachineBasicBlock::iterator SpillPt;
1244 if (DefMBB == BarrierMBB) {
1245 // Add spill after the def and the last use before the barrier.
1246 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1247 RefsInMBB, SpillIndex);
1248 if (SpillPt == DefMBB->begin())
1249 return false; // No gap to insert spill.
1251 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1252 if (SpillPt == DefMBB->end())
1253 return false; // No gap to insert spill.
1255 // Add spill. The store instruction kills the register if def is before
1256 // the barrier in the barrier block.
1257 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1258 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1259 DefMBB == BarrierMBB, SS, RC);
1260 SpillMI = prior(SpillPt);
1261 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1265 // Remember def instruction index to spill index mapping.
1266 if (DefMI && SpillMI)
1267 Def2SpillMap[ValNo->def] = SpillIndex;
1270 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1271 MachineInstr *LoadMI = prior(RestorePt);
1272 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1274 // If live interval is spilled in the same block as the barrier, just
1275 // create a hole in the interval.
1277 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
1278 // Update spill stack slot live interval.
1279 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1280 LIs->getDefIndex(RestoreIndex));
1282 UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1283 LIs->getDefIndex(RestoreIndex));
1289 // Update spill stack slot live interval.
1290 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1291 LIs->getDefIndex(RestoreIndex));
1293 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIndex);
1299 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1300 /// barrier that's being processed.
1302 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
1303 // First find all the virtual registers whose live intervals are intercepted
1304 // by the current barrier.
1305 SmallVector<LiveInterval*, 8> Intervals;
1306 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1307 if (TII->IgnoreRegisterClassBarriers(*RC))
1309 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1310 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1311 unsigned Reg = VRs[i];
1312 if (!LIs->hasInterval(Reg))
1314 LiveInterval *LI = &LIs->getInterval(Reg);
1315 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1316 // Virtual register live interval is intercepted by the barrier. We
1317 // should split and shrink wrap its interval if possible.
1318 Intervals.push_back(LI);
1322 // Process the affected live intervals.
1323 bool Change = false;
1324 while (!Intervals.empty()) {
1325 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1327 LiveInterval *LI = Intervals.back();
1328 Intervals.pop_back();
1329 Change |= SplitRegLiveInterval(LI);
1335 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1336 MachineBasicBlock* DefMBB,
1337 MachineBasicBlock* BarrierMBB) {
1338 if (DefMBB == BarrierMBB)
1341 if (LR->valno->hasPHIKill)
1344 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1345 if (LR->end < MBBEnd)
1348 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1349 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1352 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1353 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1354 typedef std::pair<MachineBasicBlock*,
1355 MachineBasicBlock::succ_iterator> ItPair;
1356 SmallVector<ItPair, 4> Stack;
1357 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1359 while (!Stack.empty()) {
1360 ItPair P = Stack.back();
1363 MachineBasicBlock* PredMBB = P.first;
1364 MachineBasicBlock::succ_iterator S = P.second;
1366 if (S == PredMBB->succ_end())
1368 else if (Visited.count(*S)) {
1369 Stack.push_back(std::make_pair(PredMBB, ++S));
1372 Stack.push_back(std::make_pair(PredMBB, S+1));
1374 MachineBasicBlock* MBB = *S;
1375 Visited.insert(MBB);
1377 if (MBB == BarrierMBB)
1380 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1381 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1382 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1384 if (MDTN == DefMDTN)
1386 else if (MDTN == BarrierMDTN)
1388 MDTN = MDTN->getIDom();
1391 MBBEnd = LIs->getMBBEndIdx(MBB);
1392 if (LR->end > MBBEnd)
1393 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1400 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1402 TM = &MF.getTarget();
1403 TII = TM->getInstrInfo();
1404 MFI = MF.getFrameInfo();
1405 MRI = &MF.getRegInfo();
1406 LIs = &getAnalysis<LiveIntervals>();
1407 LSs = &getAnalysis<LiveStacks>();
1409 bool MadeChange = false;
1411 // Make sure blocks are numbered in order.
1412 MF.RenumberBlocks();
1414 MachineBasicBlock *Entry = MF.begin();
1415 SmallPtrSet<MachineBasicBlock*,16> Visited;
1417 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1418 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1421 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1422 E = BarrierMBB->end(); I != E; ++I) {
1424 const TargetRegisterClass **BarrierRCs =
1425 Barrier->getDesc().getRegClassBarriers();
1428 BarrierIdx = LIs->getInstructionIndex(Barrier);
1429 MadeChange |= SplitRegLiveIntervals(BarrierRCs);