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);
175 } // end anonymous namespace
177 char PreAllocSplitting::ID = 0;
179 static RegisterPass<PreAllocSplitting>
180 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
182 const PassInfo *const llvm::PreAllocSplittingID = &X;
185 /// findNextEmptySlot - Find a gap after the given machine instruction in the
186 /// instruction index map. If there isn't one, return end().
187 MachineBasicBlock::iterator
188 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
189 unsigned &SpotIndex) {
190 MachineBasicBlock::iterator MII = MI;
191 if (++MII != MBB->end()) {
192 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
201 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
202 /// for spilling the current live interval. The index must be before any
203 /// defs and uses of the live interval register in the mbb. Return begin() if
205 MachineBasicBlock::iterator
206 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
208 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
209 unsigned &SpillIndex) {
210 MachineBasicBlock::iterator Pt = MBB->begin();
212 // Go top down if RefsInMBB is empty.
213 if (RefsInMBB.empty() && !DefMI) {
214 MachineBasicBlock::iterator MII = MBB->begin();
215 MachineBasicBlock::iterator EndPt = MI;
218 unsigned Index = LIs->getInstructionIndex(MII);
219 unsigned Gap = LIs->findGapBeforeInstr(Index);
225 } while (MII != EndPt);
227 MachineBasicBlock::iterator MII = MI;
228 MachineBasicBlock::iterator EndPt = DefMI
229 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
230 while (MII != EndPt && !RefsInMBB.count(MII)) {
231 unsigned Index = LIs->getInstructionIndex(MII);
232 if (LIs->hasGapBeforeInstr(Index)) {
234 SpillIndex = LIs->findGapBeforeInstr(Index, true);
243 /// findRestorePoint - Find a gap in the instruction index map that's suitable
244 /// for restoring the current live interval value. The index must be before any
245 /// uses of the live interval register in the mbb. Return end() if none is
247 MachineBasicBlock::iterator
248 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
250 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
251 unsigned &RestoreIndex) {
252 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
253 // begin index accordingly.
254 MachineBasicBlock::iterator Pt = MBB->end();
255 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
257 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
258 // the last index in the live range.
259 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
260 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
261 MachineBasicBlock::iterator EndPt = MI;
264 unsigned Index = LIs->getInstructionIndex(MII);
265 unsigned Gap = LIs->findGapBeforeInstr(Index);
272 } while (MII != EndPt);
274 MachineBasicBlock::iterator MII = MI;
276 // FIXME: Limit the number of instructions to examine to reduce
278 while (MII != MBB->end()) {
279 unsigned Index = LIs->getInstructionIndex(MII);
282 unsigned Gap = LIs->findGapBeforeInstr(Index);
287 if (RefsInMBB.count(MII))
296 /// CreateSpillStackSlot - Create a stack slot for the live interval being
297 /// split. If the live interval was previously split, just reuse the same
299 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
300 const TargetRegisterClass *RC) {
302 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
303 if (I != IntervalSSMap.end()) {
306 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
307 IntervalSSMap[Reg] = SS;
310 // Create live interval for stack slot.
311 CurrSLI = &LSs->getOrCreateInterval(SS);
312 if (CurrSLI->hasAtLeastOneValue())
313 CurrSValNo = CurrSLI->getValNumInfo(0);
315 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
319 /// IsAvailableInStack - Return true if register is available in a split stack
320 /// slot at the specified index.
322 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
323 unsigned Reg, unsigned DefIndex,
324 unsigned RestoreIndex, unsigned &SpillIndex,
329 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
330 if (I == IntervalSSMap.end())
332 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
333 if (II == Def2SpillMap.end())
336 // If last spill of def is in the same mbb as barrier mbb (where restore will
337 // be), make sure it's not below the intended restore index.
338 // FIXME: Undo the previous spill?
339 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
340 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
344 SpillIndex = II->second;
348 /// UpdateSpillSlotInterval - Given the specified val# of the register live
349 /// interval being split, and the spill and restore indicies, update the live
350 /// interval of the spill stack slot.
352 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
353 unsigned RestoreIndex) {
354 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
355 "Expect restore in the barrier mbb");
357 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
358 if (MBB == BarrierMBB) {
359 // Intra-block spill + restore. We are done.
360 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
361 CurrSLI->addRange(SLR);
365 SmallPtrSet<MachineBasicBlock*, 4> Processed;
366 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
367 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
368 CurrSLI->addRange(SLR);
369 Processed.insert(MBB);
371 // Start from the spill mbb, figure out the extend of the spill slot's
373 SmallVector<MachineBasicBlock*, 4> WorkList;
374 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
375 if (LR->end > EndIdx)
376 // If live range extend beyond end of mbb, add successors to work list.
377 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
378 SE = MBB->succ_end(); SI != SE; ++SI)
379 WorkList.push_back(*SI);
381 while (!WorkList.empty()) {
382 MachineBasicBlock *MBB = WorkList.back();
384 if (Processed.count(MBB))
386 unsigned Idx = LIs->getMBBStartIdx(MBB);
387 LR = CurrLI->getLiveRangeContaining(Idx);
388 if (LR && LR->valno == ValNo) {
389 EndIdx = LIs->getMBBEndIdx(MBB);
390 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
391 // Spill slot live interval stops at the restore.
392 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
393 CurrSLI->addRange(SLR);
394 } else if (LR->end > EndIdx) {
395 // Live range extends beyond end of mbb, process successors.
396 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
397 CurrSLI->addRange(SLR);
398 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
399 SE = MBB->succ_end(); SI != SE; ++SI)
400 WorkList.push_back(*SI);
402 LiveRange SLR(Idx, LR->end, CurrSValNo);
403 CurrSLI->addRange(SLR);
405 Processed.insert(MBB);
410 /// UpdateRegisterInterval - Given the specified val# of the current live
411 /// interval is being split, and the spill and restore indices, update the live
412 /// interval accordingly.
414 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
415 unsigned RestoreIndex) {
416 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
417 "Expect restore in the barrier mbb");
419 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
420 SmallVector<std::pair<unsigned,unsigned>, 4> After;
421 SmallVector<unsigned, 4> BeforeKills;
422 SmallVector<unsigned, 4> AfterKills;
423 SmallPtrSet<const LiveRange*, 4> Processed;
425 // First, let's figure out which parts of the live interval is now defined
426 // by the restore, which are defined by the original definition.
427 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
428 After.push_back(std::make_pair(RestoreIndex, LR->end));
429 if (CurrLI->isKill(ValNo, LR->end))
430 AfterKills.push_back(LR->end);
432 assert(LR->contains(SpillIndex));
433 if (SpillIndex > LR->start) {
434 Before.push_back(std::make_pair(LR->start, SpillIndex));
435 BeforeKills.push_back(SpillIndex);
437 Processed.insert(LR);
439 // Start from the restore mbb, figure out what part of the live interval
440 // are defined by the restore.
441 SmallVector<MachineBasicBlock*, 4> WorkList;
442 MachineBasicBlock *MBB = BarrierMBB;
443 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
444 SE = MBB->succ_end(); SI != SE; ++SI)
445 WorkList.push_back(*SI);
447 SmallPtrSet<MachineBasicBlock*, 4> ProcessedBlocks;
448 ProcessedBlocks.insert(MBB);
450 while (!WorkList.empty()) {
451 MBB = WorkList.back();
453 unsigned Idx = LIs->getMBBStartIdx(MBB);
454 LR = CurrLI->getLiveRangeContaining(Idx);
455 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
456 After.push_back(std::make_pair(LR->start, LR->end));
457 if (CurrLI->isKill(ValNo, LR->end))
458 AfterKills.push_back(LR->end);
459 Idx = LIs->getMBBEndIdx(MBB);
461 // Live range extend beyond at least one mbb. Let's see what other
463 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
465 Processed.insert(LR);
468 ProcessedBlocks.insert(MBB);
470 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
471 SE = MBB->succ_end(); SI != SE; ++SI)
472 if (!ProcessedBlocks.count(*SI))
473 WorkList.push_back(*SI);
476 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
479 if (LR->valno == ValNo && !Processed.count(LR)) {
480 Before.push_back(std::make_pair(LR->start, LR->end));
481 if (CurrLI->isKill(ValNo, LR->end))
482 BeforeKills.push_back(LR->end);
486 // Now create new val#s to represent the live ranges defined by the old def
487 // those defined by the restore.
488 unsigned AfterDef = ValNo->def;
489 MachineInstr *AfterCopy = ValNo->copy;
490 bool HasPHIKill = ValNo->hasPHIKill;
491 CurrLI->removeValNo(ValNo);
492 VNInfo *BValNo = (Before.empty())
494 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
496 CurrLI->addKills(BValNo, BeforeKills);
498 VNInfo *AValNo = (After.empty())
500 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
502 AValNo->hasPHIKill = HasPHIKill;
503 CurrLI->addKills(AValNo, AfterKills);
506 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
507 unsigned Start = Before[i].first;
508 unsigned End = Before[i].second;
509 CurrLI->addRange(LiveRange(Start, End, BValNo));
511 for (unsigned i = 0, e = After.size(); i != e; ++i) {
512 unsigned Start = After[i].first;
513 unsigned End = After[i].second;
514 CurrLI->addRange(LiveRange(Start, End, AValNo));
520 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
521 /// given block, shrink wrap the live interval to the last use (i.e. remove
522 /// from last use to the end of the mbb). In case mbb is the where the barrier
523 /// is, remove from the last use to the barrier.
525 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
526 SmallVector<MachineOperand*, 4> &Uses,
527 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
528 MachineOperand *LastMO = 0;
529 MachineInstr *LastMI = 0;
530 if (MBB != BarrierMBB && Uses.size() == 1) {
531 // Single use, no need to traverse the block. We can't assume this for the
532 // barrier bb though since the use is probably below the barrier.
534 LastMI = LastMO->getParent();
536 MachineBasicBlock::iterator MEE = MBB->begin();
537 MachineBasicBlock::iterator MII;
538 if (MBB == BarrierMBB)
544 MachineInstr *UseMI = &*MII;
545 if (!UseMIs.count(UseMI))
547 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
548 MachineOperand &MO = UseMI->getOperand(i);
549 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
559 // Cut off live range from last use (or beginning of the mbb if there
560 // are no uses in it) to the end of the mbb.
561 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
563 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
564 assert(!LastMO->isKill() && "Last use already terminates the interval?");
567 assert(MBB == BarrierMBB);
568 RangeStart = LIs->getMBBStartIdx(MBB);
570 if (MBB == BarrierMBB)
571 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
572 CurrLI->removeRange(RangeStart, RangeEnd);
574 CurrLI->addKill(ValNo, RangeStart);
576 // Return true if the last use becomes a new kill.
580 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
581 /// chain to find the new 'kills' and shrink wrap the live interval to the
582 /// new kill indices.
584 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
585 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
586 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
587 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
588 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
589 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
590 if (Visited.count(MBB))
593 // If live interval is live in another successor path, then we can't process
594 // this block. But we may able to do so after all the successors have been
596 if (MBB != BarrierMBB) {
597 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
598 SE = MBB->succ_end(); SI != SE; ++SI) {
599 MachineBasicBlock *SMBB = *SI;
602 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
609 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
610 UMII = Uses.find(MBB);
611 if (UMII != Uses.end()) {
612 // At least one use in this mbb, lets look for the kill.
613 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
614 UMII2 = UseMIs.find(MBB);
615 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
616 // Found a kill, shrink wrapping of this path ends here.
618 } else if (MBB == DefMBB) {
619 // There are no uses after the def.
620 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
621 if (UseMBBs.empty()) {
622 // The only use must be below barrier in the barrier block. It's safe to
624 LIs->RemoveMachineInstrFromMaps(DefMI);
625 DefMI->eraseFromParent();
626 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
628 } else if (MBB == BarrierMBB) {
629 // Remove entire live range from start of mbb to barrier.
630 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
631 LIs->getUseIndex(BarrierIdx)+1);
633 // Remove entire live range of the mbb out of the live interval.
634 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
638 // Reached the def mbb, stop traversing this path further.
641 // Traverse the pathes up the predecessor chains further.
642 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
643 PE = MBB->pred_end(); PI != PE; ++PI) {
644 MachineBasicBlock *Pred = *PI;
647 if (Pred == DefMBB && ValNo->hasPHIKill)
648 // Pred is the def bb and the def reaches other val#s, we must
649 // allow the value to be live out of the bb.
651 if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
653 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
654 Uses, UseMIs, UseMBBs);
661 void PreAllocSplitting::RepairLiveInterval(LiveInterval* CurrLI,
664 unsigned RestoreIdx) {
665 // Shrink wrap the live interval by walking up the CFG and find the
667 // Now let's find all the uses of the val#.
668 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
669 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
670 SmallPtrSet<MachineBasicBlock*, 4> Seen;
671 SmallVector<MachineBasicBlock*, 4> UseMBBs;
672 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
673 UE = MRI->use_end(); UI != UE; ++UI) {
674 MachineOperand &UseMO = UI.getOperand();
675 MachineInstr *UseMI = UseMO.getParent();
676 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
677 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
678 if (ULR->valno != ValNo)
680 MachineBasicBlock *UseMBB = UseMI->getParent();
681 // Remember which other mbb's use this val#.
682 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
683 UseMBBs.push_back(UseMBB);
684 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
685 UMII = Uses.find(UseMBB);
686 if (UMII != Uses.end()) {
687 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
688 UMII2 = UseMIs.find(UseMBB);
689 UMII->second.push_back(&UseMO);
690 UMII2->second.insert(UseMI);
692 SmallVector<MachineOperand*, 4> Ops;
693 Ops.push_back(&UseMO);
694 Uses.insert(std::make_pair(UseMBB, Ops));
695 SmallPtrSet<MachineInstr*, 4> MIs;
697 UseMIs.insert(std::make_pair(UseMBB, MIs));
701 // Walk up the predecessor chains.
702 SmallPtrSet<MachineBasicBlock*, 8> Visited;
703 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMI->getParent(), Visited,
704 Uses, UseMIs, UseMBBs);
706 // Remove live range from barrier to the restore. FIXME: Find a better
707 // point to re-start the live interval.
708 VNInfo* AfterValNo = UpdateRegisterInterval(ValNo,
709 LIs->getUseIndex(BarrierIdx)+1,
710 LIs->getDefIndex(RestoreIdx));
712 // Attempt to renumber the new valno into a new vreg.
713 RenumberValno(AfterValNo);
716 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
717 /// be allocated to a different register. This function creates a new vreg,
718 /// copies the valno and its live ranges over to the new vreg's interval,
719 /// removes them from the old interval, and rewrites all uses and defs of
720 /// the original reg to the new vreg within those ranges.
721 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
722 SmallVector<VNInfo*, 4> Stack;
723 SmallVector<VNInfo*, 4> VNsToCopy;
726 // Walk through and copy the valno we care about, and any other valnos
727 // that are two-address redefinitions of the one we care about. These
728 // will need to be rewritten as well. We also check for safety of the
729 // renumbering here, by making sure that none of the valno involved has
731 while (!Stack.empty()) {
732 VNInfo* OldVN = Stack.back();
735 // Bail out if we ever encounter a valno that has a PHI kill. We can't
737 if (OldVN->hasPHIKill) return;
739 VNsToCopy.push_back(OldVN);
741 // Locate two-address redefinitions
742 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
743 KE = OldVN->kills.end(); KI != KE; ++KI) {
744 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
746 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
747 if (DefIdx == ~0U) continue;
748 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
750 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
751 Stack.push_back(NextVN);
756 // Create the new vreg
757 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
759 // Create the new live interval
760 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
762 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
763 VNsToCopy.end(); OI != OE; ++OI) {
766 // Copy the valno over
767 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
768 LIs->getVNInfoAllocator());
769 NewLI.copyValNumInfo(NewVN, OldVN);
770 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
772 // Remove the valno from the old interval
773 CurrLI->removeValNo(OldVN);
776 // Rewrite defs and uses. This is done in two stages to avoid invalidating
778 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
780 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
781 E = MRI->reg_end(); I != E; ++I) {
782 MachineOperand& MO = I.getOperand();
783 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
785 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
786 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
787 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
790 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
791 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
792 MachineInstr* Inst = I->first;
793 unsigned OpIdx = I->second;
794 MachineOperand& MO = Inst->getOperand(OpIdx);
801 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
803 MachineBasicBlock::iterator RestorePt,
805 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
806 MachineBasicBlock& MBB = *RestorePt->getParent();
808 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
809 unsigned KillIdx = 0;
810 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
811 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
813 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
815 if (KillPt == DefMI->getParent()->end())
818 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
819 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
821 if (KillPt->getParent() == BarrierMBB) {
822 UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
823 LIs->getDefIndex(RestoreIdx));
830 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIdx);
837 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
838 const TargetRegisterClass* RC,
840 MachineInstr* Barrier,
841 MachineBasicBlock* MBB,
843 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
844 MachineBasicBlock::iterator Pt = MBB->begin();
846 // Go top down if RefsInMBB is empty.
847 if (RefsInMBB.empty())
850 MachineBasicBlock::iterator FoldPt = Barrier;
851 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
852 !RefsInMBB.count(FoldPt))
855 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
859 SmallVector<unsigned, 1> Ops;
860 Ops.push_back(OpIdx);
862 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
865 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
866 if (I != IntervalSSMap.end()) {
869 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
873 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
877 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
878 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
881 IntervalSSMap[vreg] = SS;
882 CurrSLI = &LSs->getOrCreateInterval(SS);
883 if (CurrSLI->hasAtLeastOneValue())
884 CurrSValNo = CurrSLI->getValNumInfo(0);
886 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
892 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
893 /// so it would not cross the barrier that's being processed. Shrink wrap
894 /// (minimize) the live interval to the last uses.
895 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
898 // Find live range where current interval cross the barrier.
899 LiveInterval::iterator LR =
900 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
901 VNInfo *ValNo = LR->valno;
903 if (ValNo->def == ~1U) {
904 // Defined by a dead def? How can this be?
905 assert(0 && "Val# is defined by a dead def?");
909 MachineInstr *DefMI = (ValNo->def != ~0U)
910 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
912 // If this would create a new join point, do not split.
913 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
916 // Find all references in the barrier mbb.
917 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
918 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
919 E = MRI->reg_end(); I != E; ++I) {
920 MachineInstr *RefMI = &*I;
921 if (RefMI->getParent() == BarrierMBB)
922 RefsInMBB.insert(RefMI);
925 // Find a point to restore the value after the barrier.
926 unsigned RestoreIndex;
927 MachineBasicBlock::iterator RestorePt =
928 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
929 if (RestorePt == BarrierMBB->end())
932 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
933 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
934 RestoreIndex, RefsInMBB))
937 // Add a spill either before the barrier or after the definition.
938 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
939 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
940 unsigned SpillIndex = 0;
941 MachineInstr *SpillMI = NULL;
943 if (ValNo->def == ~0U) {
944 // If it's defined by a phi, we must split just before the barrier.
945 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
946 BarrierMBB, SS, RefsInMBB))) {
947 SpillIndex = LIs->getInstructionIndex(SpillMI);
949 MachineBasicBlock::iterator SpillPt =
950 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
951 if (SpillPt == BarrierMBB->begin())
952 return false; // No gap to insert spill.
955 SS = CreateSpillStackSlot(CurrLI->reg, RC);
956 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
957 SpillMI = prior(SpillPt);
958 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
960 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
961 RestoreIndex, SpillIndex, SS)) {
962 // If it's already split, just restore the value. There is no need to spill
965 return false; // Def is dead. Do nothing.
967 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
968 BarrierMBB, SS, RefsInMBB))) {
969 SpillIndex = LIs->getInstructionIndex(SpillMI);
971 // Check if it's possible to insert a spill after the def MI.
972 MachineBasicBlock::iterator SpillPt;
973 if (DefMBB == BarrierMBB) {
974 // Add spill after the def and the last use before the barrier.
975 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
976 RefsInMBB, SpillIndex);
977 if (SpillPt == DefMBB->begin())
978 return false; // No gap to insert spill.
980 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
981 if (SpillPt == DefMBB->end())
982 return false; // No gap to insert spill.
984 // Add spill. The store instruction kills the register if def is before
985 // the barrier in the barrier block.
986 SS = CreateSpillStackSlot(CurrLI->reg, RC);
987 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
988 DefMBB == BarrierMBB, SS, RC);
989 SpillMI = prior(SpillPt);
990 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
994 // Remember def instruction index to spill index mapping.
995 if (DefMI && SpillMI)
996 Def2SpillMap[ValNo->def] = SpillIndex;
999 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1000 MachineInstr *LoadMI = prior(RestorePt);
1001 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1003 // If live interval is spilled in the same block as the barrier, just
1004 // create a hole in the interval.
1006 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
1007 // Update spill stack slot live interval.
1008 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1009 LIs->getDefIndex(RestoreIndex));
1011 UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1012 LIs->getDefIndex(RestoreIndex));
1018 // Update spill stack slot live interval.
1019 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1020 LIs->getDefIndex(RestoreIndex));
1022 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIndex);
1028 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1029 /// barrier that's being processed.
1031 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
1032 // First find all the virtual registers whose live intervals are intercepted
1033 // by the current barrier.
1034 SmallVector<LiveInterval*, 8> Intervals;
1035 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1036 if (TII->IgnoreRegisterClassBarriers(*RC))
1038 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1039 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1040 unsigned Reg = VRs[i];
1041 if (!LIs->hasInterval(Reg))
1043 LiveInterval *LI = &LIs->getInterval(Reg);
1044 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1045 // Virtual register live interval is intercepted by the barrier. We
1046 // should split and shrink wrap its interval if possible.
1047 Intervals.push_back(LI);
1051 // Process the affected live intervals.
1052 bool Change = false;
1053 while (!Intervals.empty()) {
1054 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1056 LiveInterval *LI = Intervals.back();
1057 Intervals.pop_back();
1058 Change |= SplitRegLiveInterval(LI);
1064 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1065 MachineBasicBlock* DefMBB,
1066 MachineBasicBlock* BarrierMBB) {
1067 if (DefMBB == BarrierMBB)
1070 if (LR->valno->hasPHIKill)
1073 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1074 if (LR->end < MBBEnd)
1077 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1078 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1081 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1082 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1083 typedef std::pair<MachineBasicBlock*,
1084 MachineBasicBlock::succ_iterator> ItPair;
1085 SmallVector<ItPair, 4> Stack;
1086 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1088 while (!Stack.empty()) {
1089 ItPair P = Stack.back();
1092 MachineBasicBlock* PredMBB = P.first;
1093 MachineBasicBlock::succ_iterator S = P.second;
1095 if (S == PredMBB->succ_end())
1097 else if (Visited.count(*S)) {
1098 Stack.push_back(std::make_pair(PredMBB, ++S));
1101 Stack.push_back(std::make_pair(PredMBB, S+1));
1103 MachineBasicBlock* MBB = *S;
1104 Visited.insert(MBB);
1106 if (MBB == BarrierMBB)
1109 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1110 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1111 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1113 if (MDTN == DefMDTN)
1115 else if (MDTN == BarrierMDTN)
1117 MDTN = MDTN->getIDom();
1120 MBBEnd = LIs->getMBBEndIdx(MBB);
1121 if (LR->end > MBBEnd)
1122 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1129 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1131 TM = &MF.getTarget();
1132 TII = TM->getInstrInfo();
1133 MFI = MF.getFrameInfo();
1134 MRI = &MF.getRegInfo();
1135 LIs = &getAnalysis<LiveIntervals>();
1136 LSs = &getAnalysis<LiveStacks>();
1138 bool MadeChange = false;
1140 // Make sure blocks are numbered in order.
1141 MF.RenumberBlocks();
1143 MachineBasicBlock *Entry = MF.begin();
1144 SmallPtrSet<MachineBasicBlock*,16> Visited;
1146 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1147 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1150 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1151 E = BarrierMBB->end(); I != E; ++I) {
1153 const TargetRegisterClass **BarrierRCs =
1154 Barrier->getDesc().getRegClassBarriers();
1157 BarrierIdx = LIs->getInstructionIndex(Barrier);
1158 MadeChange |= SplitRegLiveIntervals(BarrierRCs);