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");
44 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
45 MachineFunction *CurrMF;
46 const TargetMachine *TM;
47 const TargetInstrInfo *TII;
48 MachineFrameInfo *MFI;
49 MachineRegisterInfo *MRI;
53 // Barrier - Current barrier being processed.
54 MachineInstr *Barrier;
56 // BarrierMBB - Basic block where the barrier resides in.
57 MachineBasicBlock *BarrierMBB;
59 // Barrier - Current barrier index.
62 // CurrLI - Current live interval being split.
65 // CurrSLI - Current stack slot live interval.
66 LiveInterval *CurrSLI;
68 // CurrSValNo - Current val# for the stack slot live interval.
71 // IntervalSSMap - A map from live interval to spill slots.
72 DenseMap<unsigned, int> IntervalSSMap;
74 // Def2SpillMap - A map from a def instruction index to spill index.
75 DenseMap<unsigned, unsigned> Def2SpillMap;
79 PreAllocSplitting() : MachineFunctionPass(&ID) {}
81 virtual bool runOnMachineFunction(MachineFunction &MF);
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequired<LiveIntervals>();
85 AU.addPreserved<LiveIntervals>();
86 AU.addRequired<LiveStacks>();
87 AU.addPreserved<LiveStacks>();
88 AU.addPreserved<RegisterCoalescer>();
90 AU.addPreservedID(StrongPHIEliminationID);
92 AU.addPreservedID(PHIEliminationID);
93 AU.addRequired<MachineDominatorTree>();
94 AU.addRequired<MachineLoopInfo>();
95 AU.addPreserved<MachineDominatorTree>();
96 AU.addPreserved<MachineLoopInfo>();
97 MachineFunctionPass::getAnalysisUsage(AU);
100 virtual void releaseMemory() {
101 IntervalSSMap.clear();
102 Def2SpillMap.clear();
105 virtual const char *getPassName() const {
106 return "Pre-Register Allocaton Live Interval Splitting";
109 /// print - Implement the dump method.
110 virtual void print(std::ostream &O, const Module* M = 0) const {
114 void print(std::ostream *O, const Module* M = 0) const {
119 MachineBasicBlock::iterator
120 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
123 MachineBasicBlock::iterator
124 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
125 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
127 MachineBasicBlock::iterator
128 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
129 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
131 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
133 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
134 unsigned&, int&) const;
136 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
138 void UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
140 bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
141 SmallVector<MachineOperand*, 4>&,
142 SmallPtrSet<MachineInstr*, 4>&);
144 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
145 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
146 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
147 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
148 SmallVector<MachineBasicBlock*, 4>&);
150 bool SplitRegLiveInterval(LiveInterval*);
152 bool SplitRegLiveIntervals(const TargetRegisterClass **);
154 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
155 MachineBasicBlock* BarrierMBB);
157 } // end anonymous namespace
159 char PreAllocSplitting::ID = 0;
161 static RegisterPass<PreAllocSplitting>
162 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
164 const PassInfo *const llvm::PreAllocSplittingID = &X;
167 /// findNextEmptySlot - Find a gap after the given machine instruction in the
168 /// instruction index map. If there isn't one, return end().
169 MachineBasicBlock::iterator
170 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
171 unsigned &SpotIndex) {
172 MachineBasicBlock::iterator MII = MI;
173 if (++MII != MBB->end()) {
174 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
183 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
184 /// for spilling the current live interval. The index must be before any
185 /// defs and uses of the live interval register in the mbb. Return begin() if
187 MachineBasicBlock::iterator
188 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
190 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
191 unsigned &SpillIndex) {
192 MachineBasicBlock::iterator Pt = MBB->begin();
194 // Go top down if RefsInMBB is empty.
195 if (RefsInMBB.empty() && !DefMI) {
196 MachineBasicBlock::iterator MII = MBB->begin();
197 MachineBasicBlock::iterator EndPt = MI;
200 unsigned Index = LIs->getInstructionIndex(MII);
201 unsigned Gap = LIs->findGapBeforeInstr(Index);
207 } while (MII != EndPt);
209 MachineBasicBlock::iterator MII = MI;
210 MachineBasicBlock::iterator EndPt = DefMI
211 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
212 while (MII != EndPt && !RefsInMBB.count(MII)) {
213 unsigned Index = LIs->getInstructionIndex(MII);
214 if (LIs->hasGapBeforeInstr(Index)) {
216 SpillIndex = LIs->findGapBeforeInstr(Index, true);
225 /// findRestorePoint - Find a gap in the instruction index map that's suitable
226 /// for restoring the current live interval value. The index must be before any
227 /// uses of the live interval register in the mbb. Return end() if none is
229 MachineBasicBlock::iterator
230 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
232 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
233 unsigned &RestoreIndex) {
234 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
235 // begin index accordingly.
236 MachineBasicBlock::iterator Pt = MBB->end();
237 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
239 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
240 // the last index in the live range.
241 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
242 MachineBasicBlock::iterator MII = MBB->end();
243 MachineBasicBlock::iterator EndPt = MI;
246 unsigned Index = LIs->getInstructionIndex(MII);
247 unsigned Gap = LIs->findGapBeforeInstr(Index);
254 } while (MII != EndPt);
256 MachineBasicBlock::iterator MII = MI;
258 // FIXME: Limit the number of instructions to examine to reduce
260 while (MII != MBB->end()) {
261 unsigned Index = LIs->getInstructionIndex(MII);
264 unsigned Gap = LIs->findGapBeforeInstr(Index);
269 if (RefsInMBB.count(MII))
278 /// CreateSpillStackSlot - Create a stack slot for the live interval being
279 /// split. If the live interval was previously split, just reuse the same
281 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
282 const TargetRegisterClass *RC) {
284 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
285 if (I != IntervalSSMap.end()) {
288 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
289 IntervalSSMap[Reg] = SS;
292 // Create live interval for stack slot.
293 CurrSLI = &LSs->getOrCreateInterval(SS);
294 if (CurrSLI->hasAtLeastOneValue())
295 CurrSValNo = CurrSLI->getValNumInfo(0);
297 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
301 /// IsAvailableInStack - Return true if register is available in a split stack
302 /// slot at the specified index.
304 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
305 unsigned Reg, unsigned DefIndex,
306 unsigned RestoreIndex, unsigned &SpillIndex,
311 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
312 if (I == IntervalSSMap.end())
314 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
315 if (II == Def2SpillMap.end())
318 // If last spill of def is in the same mbb as barrier mbb (where restore will
319 // be), make sure it's not below the intended restore index.
320 // FIXME: Undo the previous spill?
321 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
322 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
326 SpillIndex = II->second;
330 /// UpdateSpillSlotInterval - Given the specified val# of the register live
331 /// interval being split, and the spill and restore indicies, update the live
332 /// interval of the spill stack slot.
334 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
335 unsigned RestoreIndex) {
336 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
337 "Expect restore in the barrier mbb");
339 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
340 if (MBB == BarrierMBB) {
341 // Intra-block spill + restore. We are done.
342 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
343 CurrSLI->addRange(SLR);
347 SmallPtrSet<MachineBasicBlock*, 4> Processed;
348 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
349 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
350 CurrSLI->addRange(SLR);
351 Processed.insert(MBB);
353 // Start from the spill mbb, figure out the extend of the spill slot's
355 SmallVector<MachineBasicBlock*, 4> WorkList;
356 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
357 if (LR->end > EndIdx)
358 // If live range extend beyond end of mbb, add successors to work list.
359 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
360 SE = MBB->succ_end(); SI != SE; ++SI)
361 WorkList.push_back(*SI);
363 while (!WorkList.empty()) {
364 MachineBasicBlock *MBB = WorkList.back();
366 if (Processed.count(MBB))
368 unsigned Idx = LIs->getMBBStartIdx(MBB);
369 LR = CurrLI->getLiveRangeContaining(Idx);
370 if (LR && LR->valno == ValNo) {
371 EndIdx = LIs->getMBBEndIdx(MBB);
372 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
373 // Spill slot live interval stops at the restore.
374 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
375 CurrSLI->addRange(SLR);
376 } else if (LR->end > EndIdx) {
377 // Live range extends beyond end of mbb, process successors.
378 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
379 CurrSLI->addRange(SLR);
380 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
381 SE = MBB->succ_end(); SI != SE; ++SI)
382 WorkList.push_back(*SI);
384 LiveRange SLR(Idx, LR->end, CurrSValNo);
385 CurrSLI->addRange(SLR);
387 Processed.insert(MBB);
392 /// UpdateRegisterInterval - Given the specified val# of the current live
393 /// interval is being split, and the spill and restore indices, update the live
394 /// interval accordingly.
396 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
397 unsigned RestoreIndex) {
398 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
399 "Expect restore in the barrier mbb");
401 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
402 SmallVector<std::pair<unsigned,unsigned>, 4> After;
403 SmallVector<unsigned, 4> BeforeKills;
404 SmallVector<unsigned, 4> AfterKills;
405 SmallPtrSet<const LiveRange*, 4> Processed;
407 // First, let's figure out which parts of the live interval is now defined
408 // by the restore, which are defined by the original definition.
409 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
410 After.push_back(std::make_pair(RestoreIndex, LR->end));
411 if (CurrLI->isKill(ValNo, LR->end))
412 AfterKills.push_back(LR->end);
414 assert(LR->contains(SpillIndex));
415 if (SpillIndex > LR->start) {
416 Before.push_back(std::make_pair(LR->start, SpillIndex));
417 BeforeKills.push_back(SpillIndex);
419 Processed.insert(LR);
421 // Start from the restore mbb, figure out what part of the live interval
422 // are defined by the restore.
423 SmallVector<MachineBasicBlock*, 4> WorkList;
424 MachineBasicBlock *MBB = BarrierMBB;
425 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
426 SE = MBB->succ_end(); SI != SE; ++SI)
427 WorkList.push_back(*SI);
429 while (!WorkList.empty()) {
430 MBB = WorkList.back();
432 unsigned Idx = LIs->getMBBStartIdx(MBB);
433 LR = CurrLI->getLiveRangeContaining(Idx);
434 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
435 After.push_back(std::make_pair(LR->start, LR->end));
436 if (CurrLI->isKill(ValNo, LR->end))
437 AfterKills.push_back(LR->end);
438 Idx = LIs->getMBBEndIdx(MBB);
440 // Live range extend beyond at least one mbb. Let's see what other
442 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
444 Processed.insert(LR);
448 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
451 if (LR->valno == ValNo && !Processed.count(LR)) {
452 Before.push_back(std::make_pair(LR->start, LR->end));
453 if (CurrLI->isKill(ValNo, LR->end))
454 BeforeKills.push_back(LR->end);
458 // Now create new val#s to represent the live ranges defined by the old def
459 // those defined by the restore.
460 unsigned AfterDef = ValNo->def;
461 MachineInstr *AfterCopy = ValNo->copy;
462 bool HasPHIKill = ValNo->hasPHIKill;
463 CurrLI->removeValNo(ValNo);
464 VNInfo *BValNo = (Before.empty())
466 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
468 CurrLI->addKills(BValNo, BeforeKills);
470 VNInfo *AValNo = (After.empty())
472 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
474 AValNo->hasPHIKill = HasPHIKill;
475 CurrLI->addKills(AValNo, AfterKills);
478 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
479 unsigned Start = Before[i].first;
480 unsigned End = Before[i].second;
481 CurrLI->addRange(LiveRange(Start, End, BValNo));
483 for (unsigned i = 0, e = After.size(); i != e; ++i) {
484 unsigned Start = After[i].first;
485 unsigned End = After[i].second;
486 CurrLI->addRange(LiveRange(Start, End, AValNo));
490 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
491 /// given block, shrink wrap the live interval to the last use (i.e. remove
492 /// from last use to the end of the mbb). In case mbb is the where the barrier
493 /// is, remove from the last use to the barrier.
495 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
496 SmallVector<MachineOperand*, 4> &Uses,
497 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
498 MachineOperand *LastMO = 0;
499 MachineInstr *LastMI = 0;
500 if (MBB != BarrierMBB && Uses.size() == 1) {
501 // Single use, no need to traverse the block. We can't assume this for the
502 // barrier bb though since the use is probably below the barrier.
504 LastMI = LastMO->getParent();
506 MachineBasicBlock::iterator MEE = MBB->begin();
507 MachineBasicBlock::iterator MII;
508 if (MBB == BarrierMBB)
514 MachineInstr *UseMI = &*MII;
515 if (!UseMIs.count(UseMI))
517 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
518 MachineOperand &MO = UseMI->getOperand(i);
519 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
529 // Cut off live range from last use (or beginning of the mbb if there
530 // are no uses in it) to the end of the mbb.
531 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
533 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
534 assert(!LastMO->isKill() && "Last use already terminates the interval?");
537 assert(MBB == BarrierMBB);
538 RangeStart = LIs->getMBBStartIdx(MBB);
540 if (MBB == BarrierMBB)
541 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
542 CurrLI->removeRange(RangeStart, RangeEnd);
544 CurrLI->addKill(ValNo, RangeStart);
546 // Return true if the last use becomes a new kill.
550 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
551 /// chain to find the new 'kills' and shrink wrap the live interval to the
552 /// new kill indices.
554 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
555 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
556 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
557 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
558 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
559 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
560 if (Visited.count(MBB))
563 // If live interval is live in another successor path, then we can't process
564 // this block. But we may able to do so after all the successors have been
566 if (MBB != BarrierMBB) {
567 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
568 SE = MBB->succ_end(); SI != SE; ++SI) {
569 MachineBasicBlock *SMBB = *SI;
572 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
579 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
580 UMII = Uses.find(MBB);
581 if (UMII != Uses.end()) {
582 // At least one use in this mbb, lets look for the kill.
583 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
584 UMII2 = UseMIs.find(MBB);
585 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
586 // Found a kill, shrink wrapping of this path ends here.
588 } else if (MBB == DefMBB) {
589 // There are no uses after the def.
590 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
591 if (UseMBBs.empty()) {
592 // The only use must be below barrier in the barrier block. It's safe to
594 LIs->RemoveMachineInstrFromMaps(DefMI);
595 DefMI->eraseFromParent();
596 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
598 } else if (MBB == BarrierMBB) {
599 // Remove entire live range from start of mbb to barrier.
600 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
601 LIs->getUseIndex(BarrierIdx)+1);
603 // Remove entire live range of the mbb out of the live interval.
604 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
608 // Reached the def mbb, stop traversing this path further.
611 // Traverse the pathes up the predecessor chains further.
612 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
613 PE = MBB->pred_end(); PI != PE; ++PI) {
614 MachineBasicBlock *Pred = *PI;
617 if (Pred == DefMBB && ValNo->hasPHIKill)
618 // Pred is the def bb and the def reaches other val#s, we must
619 // allow the value to be live out of the bb.
621 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
622 Uses, UseMIs, UseMBBs);
628 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
629 /// so it would not cross the barrier that's being processed. Shrink wrap
630 /// (minimize) the live interval to the last uses.
631 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
634 // Find live range where current interval cross the barrier.
635 LiveInterval::iterator LR =
636 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
637 VNInfo *ValNo = LR->valno;
639 if (ValNo->def == ~1U) {
640 // Defined by a dead def? How can this be?
641 assert(0 && "Val# is defined by a dead def?");
645 // FIXME: For now, if definition is rematerializable, do not split.
646 MachineInstr *DefMI = (ValNo->def != ~0U)
647 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
648 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
651 // If this would create a new join point, do not split.
652 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
655 // Find all references in the barrier mbb.
656 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
657 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
658 E = MRI->reg_end(); I != E; ++I) {
659 MachineInstr *RefMI = &*I;
660 if (RefMI->getParent() == BarrierMBB)
661 RefsInMBB.insert(RefMI);
664 // Find a point to restore the value after the barrier.
665 unsigned RestoreIndex;
666 MachineBasicBlock::iterator RestorePt =
667 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
668 if (RestorePt == BarrierMBB->end())
671 // Add a spill either before the barrier or after the definition.
672 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
673 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
674 unsigned SpillIndex = 0;
675 MachineInstr *SpillMI = NULL;
677 if (ValNo->def == ~0U) {
678 // If it's defined by a phi, we must split just before the barrier.
679 MachineBasicBlock::iterator SpillPt =
680 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
681 if (SpillPt == BarrierMBB->begin())
682 return false; // No gap to insert spill.
684 SS = CreateSpillStackSlot(CurrLI->reg, RC);
685 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
686 SpillMI = prior(SpillPt);
687 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
688 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
689 RestoreIndex, SpillIndex, SS)) {
690 // If it's already split, just restore the value. There is no need to spill
693 return false; // Def is dead. Do nothing.
694 // Check if it's possible to insert a spill after the def MI.
695 MachineBasicBlock::iterator SpillPt;
696 if (DefMBB == BarrierMBB) {
697 // Add spill after the def and the last use before the barrier.
698 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI, RefsInMBB, SpillIndex);
699 if (SpillPt == DefMBB->begin())
700 return false; // No gap to insert spill.
702 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
703 if (SpillPt == DefMBB->end())
704 return false; // No gap to insert spill.
706 // Add spill. The store instruction kills the register if def is before
707 // the barrier in the barrier block.
708 SS = CreateSpillStackSlot(CurrLI->reg, RC);
709 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
710 DefMBB == BarrierMBB, SS, RC);
711 SpillMI = prior(SpillPt);
712 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
715 // Remember def instruction index to spill index mapping.
716 if (DefMI && SpillMI)
717 Def2SpillMap[ValNo->def] = SpillIndex;
720 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
721 MachineInstr *LoadMI = prior(RestorePt);
722 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
724 // If live interval is spilled in the same block as the barrier, just
725 // create a hole in the interval.
727 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
728 // Update spill stack slot live interval.
729 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
730 LIs->getDefIndex(RestoreIndex));
732 UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
733 LIs->getDefIndex(RestoreIndex));
739 // Update spill stack slot live interval.
740 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
741 LIs->getDefIndex(RestoreIndex));
743 // Shrink wrap the live interval by walking up the CFG and find the
745 // Now let's find all the uses of the val#.
746 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
747 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
748 SmallPtrSet<MachineBasicBlock*, 4> Seen;
749 SmallVector<MachineBasicBlock*, 4> UseMBBs;
750 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
751 UE = MRI->use_end(); UI != UE; ++UI) {
752 MachineOperand &UseMO = UI.getOperand();
753 MachineInstr *UseMI = UseMO.getParent();
754 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
755 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
756 if (ULR->valno != ValNo)
758 MachineBasicBlock *UseMBB = UseMI->getParent();
759 // Remember which other mbb's use this val#.
760 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
761 UseMBBs.push_back(UseMBB);
762 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
763 UMII = Uses.find(UseMBB);
764 if (UMII != Uses.end()) {
765 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
766 UMII2 = UseMIs.find(UseMBB);
767 UMII->second.push_back(&UseMO);
768 UMII2->second.insert(UseMI);
770 SmallVector<MachineOperand*, 4> Ops;
771 Ops.push_back(&UseMO);
772 Uses.insert(std::make_pair(UseMBB, Ops));
773 SmallPtrSet<MachineInstr*, 4> MIs;
775 UseMIs.insert(std::make_pair(UseMBB, MIs));
779 // Walk up the predecessor chains.
780 SmallPtrSet<MachineBasicBlock*, 8> Visited;
781 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMBB, Visited,
782 Uses, UseMIs, UseMBBs);
784 // FIXME: If ValNo->hasPHIKill is false, then renumber the val# by
787 // Remove live range from barrier to the restore. FIXME: Find a better
788 // point to re-start the live interval.
789 UpdateRegisterInterval(ValNo, LIs->getUseIndex(BarrierIdx)+1,
790 LIs->getDefIndex(RestoreIndex));
796 /// SplitRegLiveIntervals - Split all register live intervals that cross the
797 /// barrier that's being processed.
799 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
800 // First find all the virtual registers whose live intervals are intercepted
801 // by the current barrier.
802 SmallVector<LiveInterval*, 8> Intervals;
803 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
804 if (TII->IgnoreRegisterClassBarriers(*RC))
806 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
807 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
808 unsigned Reg = VRs[i];
809 if (!LIs->hasInterval(Reg))
811 LiveInterval *LI = &LIs->getInterval(Reg);
812 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
813 // Virtual register live interval is intercepted by the barrier. We
814 // should split and shrink wrap its interval if possible.
815 Intervals.push_back(LI);
819 // Process the affected live intervals.
821 while (!Intervals.empty()) {
822 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
824 LiveInterval *LI = Intervals.back();
825 Intervals.pop_back();
826 Change |= SplitRegLiveInterval(LI);
832 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
833 MachineBasicBlock* DefMBB,
834 MachineBasicBlock* BarrierMBB) {
835 if (DefMBB == BarrierMBB)
838 if (LR->valno->hasPHIKill)
841 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
842 if (LR->end < MBBEnd)
845 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
846 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
849 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
850 SmallPtrSet<MachineBasicBlock*, 4> Visited;
851 typedef std::pair<MachineBasicBlock*,
852 MachineBasicBlock::succ_iterator> ItPair;
853 SmallVector<ItPair, 4> Stack;
854 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
856 while (!Stack.empty()) {
857 ItPair P = Stack.back();
860 MachineBasicBlock* PredMBB = P.first;
861 MachineBasicBlock::succ_iterator S = P.second;
863 if (S == PredMBB->succ_end())
865 else if (Visited.count(*S)) {
866 Stack.push_back(std::make_pair(PredMBB, ++S));
869 Stack.push_back(std::make_pair(PredMBB, S+1));
871 MachineBasicBlock* MBB = *S;
874 if (MBB == BarrierMBB)
877 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
878 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
879 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
883 else if (MDTN == BarrierMDTN)
885 MDTN = MDTN->getIDom();
888 MBBEnd = LIs->getMBBEndIdx(MBB);
889 if (LR->end > MBBEnd)
890 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
897 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
899 TM = &MF.getTarget();
900 TII = TM->getInstrInfo();
901 MFI = MF.getFrameInfo();
902 MRI = &MF.getRegInfo();
903 LIs = &getAnalysis<LiveIntervals>();
904 LSs = &getAnalysis<LiveStacks>();
906 bool MadeChange = false;
908 // Make sure blocks are numbered in order.
912 // FIXME: Go top down.
913 MachineBasicBlock *Entry = MF.begin();
914 SmallPtrSet<MachineBasicBlock*,16> Visited;
916 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
917 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
920 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
921 E = BarrierMBB->end(); I != E; ++I) {
923 const TargetRegisterClass **BarrierRCs =
924 Barrier->getDesc().getRegClassBarriers();
927 BarrierIdx = LIs->getInstructionIndex(Barrier);
928 MadeChange |= SplitRegLiveIntervals(BarrierRCs);
932 for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
935 for (MachineBasicBlock::reverse_iterator II = BarrierMBB->rbegin(),
936 EE = BarrierMBB->rend(); II != EE; ++II) {
938 const TargetRegisterClass **BarrierRCs =
939 Barrier->getDesc().getRegClassBarriers();
942 BarrierIdx = LIs->getInstructionIndex(Barrier);
943 MadeChange |= SplitRegLiveIntervals(BarrierRCs);