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");
45 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
46 MachineFunction *CurrMF;
47 const TargetMachine *TM;
48 const TargetInstrInfo *TII;
49 MachineFrameInfo *MFI;
50 MachineRegisterInfo *MRI;
54 // Barrier - Current barrier being processed.
55 MachineInstr *Barrier;
57 // BarrierMBB - Basic block where the barrier resides in.
58 MachineBasicBlock *BarrierMBB;
60 // Barrier - Current barrier index.
63 // CurrLI - Current live interval being split.
66 // CurrSLI - Current stack slot live interval.
67 LiveInterval *CurrSLI;
69 // CurrSValNo - Current val# for the stack slot live interval.
72 // IntervalSSMap - A map from live interval to spill slots.
73 DenseMap<unsigned, int> IntervalSSMap;
75 // Def2SpillMap - A map from a def instruction index to spill index.
76 DenseMap<unsigned, unsigned> Def2SpillMap;
80 PreAllocSplitting() : MachineFunctionPass(&ID) {}
82 virtual bool runOnMachineFunction(MachineFunction &MF);
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LiveIntervals>();
86 AU.addPreserved<LiveIntervals>();
87 AU.addRequired<LiveStacks>();
88 AU.addPreserved<LiveStacks>();
89 AU.addPreserved<RegisterCoalescer>();
91 AU.addPreservedID(StrongPHIEliminationID);
93 AU.addPreservedID(PHIEliminationID);
94 AU.addRequired<MachineDominatorTree>();
95 AU.addRequired<MachineLoopInfo>();
96 AU.addPreserved<MachineDominatorTree>();
97 AU.addPreserved<MachineLoopInfo>();
98 MachineFunctionPass::getAnalysisUsage(AU);
101 virtual void releaseMemory() {
102 IntervalSSMap.clear();
103 Def2SpillMap.clear();
106 virtual const char *getPassName() const {
107 return "Pre-Register Allocaton Live Interval Splitting";
110 /// print - Implement the dump method.
111 virtual void print(std::ostream &O, const Module* M = 0) const {
115 void print(std::ostream *O, const Module* M = 0) const {
120 MachineBasicBlock::iterator
121 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
124 MachineBasicBlock::iterator
125 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
126 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
128 MachineBasicBlock::iterator
129 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
130 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
132 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
134 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
135 unsigned&, int&) const;
137 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
139 void UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
141 bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
142 SmallVector<MachineOperand*, 4>&,
143 SmallPtrSet<MachineInstr*, 4>&);
145 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
146 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
147 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
148 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
149 SmallVector<MachineBasicBlock*, 4>&);
151 bool SplitRegLiveInterval(LiveInterval*);
153 bool SplitRegLiveIntervals(const TargetRegisterClass **);
155 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
156 MachineBasicBlock* BarrierMBB);
157 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
159 MachineBasicBlock::iterator RestorePt,
161 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
163 } // end anonymous namespace
165 char PreAllocSplitting::ID = 0;
167 static RegisterPass<PreAllocSplitting>
168 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
170 const PassInfo *const llvm::PreAllocSplittingID = &X;
173 /// findNextEmptySlot - Find a gap after the given machine instruction in the
174 /// instruction index map. If there isn't one, return end().
175 MachineBasicBlock::iterator
176 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
177 unsigned &SpotIndex) {
178 MachineBasicBlock::iterator MII = MI;
179 if (++MII != MBB->end()) {
180 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
189 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
190 /// for spilling the current live interval. The index must be before any
191 /// defs and uses of the live interval register in the mbb. Return begin() if
193 MachineBasicBlock::iterator
194 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
196 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
197 unsigned &SpillIndex) {
198 MachineBasicBlock::iterator Pt = MBB->begin();
200 // Go top down if RefsInMBB is empty.
201 if (RefsInMBB.empty() && !DefMI) {
202 MachineBasicBlock::iterator MII = MBB->begin();
203 MachineBasicBlock::iterator EndPt = MI;
206 unsigned Index = LIs->getInstructionIndex(MII);
207 unsigned Gap = LIs->findGapBeforeInstr(Index);
213 } while (MII != EndPt);
215 MachineBasicBlock::iterator MII = MI;
216 MachineBasicBlock::iterator EndPt = DefMI
217 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
218 while (MII != EndPt && !RefsInMBB.count(MII)) {
219 unsigned Index = LIs->getInstructionIndex(MII);
220 if (LIs->hasGapBeforeInstr(Index)) {
222 SpillIndex = LIs->findGapBeforeInstr(Index, true);
231 /// findRestorePoint - Find a gap in the instruction index map that's suitable
232 /// for restoring the current live interval value. The index must be before any
233 /// uses of the live interval register in the mbb. Return end() if none is
235 MachineBasicBlock::iterator
236 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
238 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
239 unsigned &RestoreIndex) {
240 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
241 // begin index accordingly.
242 MachineBasicBlock::iterator Pt = MBB->end();
243 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
245 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
246 // the last index in the live range.
247 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
248 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
249 MachineBasicBlock::iterator EndPt = MI;
252 unsigned Index = LIs->getInstructionIndex(MII);
253 unsigned Gap = LIs->findGapBeforeInstr(Index);
260 } while (MII != EndPt);
262 MachineBasicBlock::iterator MII = MI;
264 // FIXME: Limit the number of instructions to examine to reduce
266 while (MII != MBB->end()) {
267 unsigned Index = LIs->getInstructionIndex(MII);
270 unsigned Gap = LIs->findGapBeforeInstr(Index);
275 if (RefsInMBB.count(MII))
284 /// CreateSpillStackSlot - Create a stack slot for the live interval being
285 /// split. If the live interval was previously split, just reuse the same
287 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
288 const TargetRegisterClass *RC) {
290 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
291 if (I != IntervalSSMap.end()) {
294 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
295 IntervalSSMap[Reg] = SS;
298 // Create live interval for stack slot.
299 CurrSLI = &LSs->getOrCreateInterval(SS);
300 if (CurrSLI->hasAtLeastOneValue())
301 CurrSValNo = CurrSLI->getValNumInfo(0);
303 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
307 /// IsAvailableInStack - Return true if register is available in a split stack
308 /// slot at the specified index.
310 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
311 unsigned Reg, unsigned DefIndex,
312 unsigned RestoreIndex, unsigned &SpillIndex,
317 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
318 if (I == IntervalSSMap.end())
320 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
321 if (II == Def2SpillMap.end())
324 // If last spill of def is in the same mbb as barrier mbb (where restore will
325 // be), make sure it's not below the intended restore index.
326 // FIXME: Undo the previous spill?
327 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
328 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
332 SpillIndex = II->second;
336 /// UpdateSpillSlotInterval - Given the specified val# of the register live
337 /// interval being split, and the spill and restore indicies, update the live
338 /// interval of the spill stack slot.
340 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
341 unsigned RestoreIndex) {
342 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
343 "Expect restore in the barrier mbb");
345 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
346 if (MBB == BarrierMBB) {
347 // Intra-block spill + restore. We are done.
348 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
349 CurrSLI->addRange(SLR);
353 SmallPtrSet<MachineBasicBlock*, 4> Processed;
354 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
355 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
356 CurrSLI->addRange(SLR);
357 Processed.insert(MBB);
359 // Start from the spill mbb, figure out the extend of the spill slot's
361 SmallVector<MachineBasicBlock*, 4> WorkList;
362 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
363 if (LR->end > EndIdx)
364 // If live range extend beyond end of mbb, add successors to work list.
365 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
366 SE = MBB->succ_end(); SI != SE; ++SI)
367 WorkList.push_back(*SI);
369 while (!WorkList.empty()) {
370 MachineBasicBlock *MBB = WorkList.back();
372 if (Processed.count(MBB))
374 unsigned Idx = LIs->getMBBStartIdx(MBB);
375 LR = CurrLI->getLiveRangeContaining(Idx);
376 if (LR && LR->valno == ValNo) {
377 EndIdx = LIs->getMBBEndIdx(MBB);
378 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
379 // Spill slot live interval stops at the restore.
380 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
381 CurrSLI->addRange(SLR);
382 } else if (LR->end > EndIdx) {
383 // Live range extends beyond end of mbb, process successors.
384 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
385 CurrSLI->addRange(SLR);
386 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
387 SE = MBB->succ_end(); SI != SE; ++SI)
388 WorkList.push_back(*SI);
390 LiveRange SLR(Idx, LR->end, CurrSValNo);
391 CurrSLI->addRange(SLR);
393 Processed.insert(MBB);
398 /// UpdateRegisterInterval - Given the specified val# of the current live
399 /// interval is being split, and the spill and restore indices, update the live
400 /// interval accordingly.
402 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
403 unsigned RestoreIndex) {
404 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
405 "Expect restore in the barrier mbb");
407 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
408 SmallVector<std::pair<unsigned,unsigned>, 4> After;
409 SmallVector<unsigned, 4> BeforeKills;
410 SmallVector<unsigned, 4> AfterKills;
411 SmallPtrSet<const LiveRange*, 4> Processed;
413 // First, let's figure out which parts of the live interval is now defined
414 // by the restore, which are defined by the original definition.
415 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
416 After.push_back(std::make_pair(RestoreIndex, LR->end));
417 if (CurrLI->isKill(ValNo, LR->end))
418 AfterKills.push_back(LR->end);
420 assert(LR->contains(SpillIndex));
421 if (SpillIndex > LR->start) {
422 Before.push_back(std::make_pair(LR->start, SpillIndex));
423 BeforeKills.push_back(SpillIndex);
425 Processed.insert(LR);
427 // Start from the restore mbb, figure out what part of the live interval
428 // are defined by the restore.
429 SmallVector<MachineBasicBlock*, 4> WorkList;
430 MachineBasicBlock *MBB = BarrierMBB;
431 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
432 SE = MBB->succ_end(); SI != SE; ++SI)
433 WorkList.push_back(*SI);
435 while (!WorkList.empty()) {
436 MBB = WorkList.back();
438 unsigned Idx = LIs->getMBBStartIdx(MBB);
439 LR = CurrLI->getLiveRangeContaining(Idx);
440 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
441 After.push_back(std::make_pair(LR->start, LR->end));
442 if (CurrLI->isKill(ValNo, LR->end))
443 AfterKills.push_back(LR->end);
444 Idx = LIs->getMBBEndIdx(MBB);
446 // Live range extend beyond at least one mbb. Let's see what other
448 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
450 Processed.insert(LR);
454 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
457 if (LR->valno == ValNo && !Processed.count(LR)) {
458 Before.push_back(std::make_pair(LR->start, LR->end));
459 if (CurrLI->isKill(ValNo, LR->end))
460 BeforeKills.push_back(LR->end);
464 // Now create new val#s to represent the live ranges defined by the old def
465 // those defined by the restore.
466 unsigned AfterDef = ValNo->def;
467 MachineInstr *AfterCopy = ValNo->copy;
468 bool HasPHIKill = ValNo->hasPHIKill;
469 CurrLI->removeValNo(ValNo);
470 VNInfo *BValNo = (Before.empty())
472 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
474 CurrLI->addKills(BValNo, BeforeKills);
476 VNInfo *AValNo = (After.empty())
478 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
480 AValNo->hasPHIKill = HasPHIKill;
481 CurrLI->addKills(AValNo, AfterKills);
484 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
485 unsigned Start = Before[i].first;
486 unsigned End = Before[i].second;
487 CurrLI->addRange(LiveRange(Start, End, BValNo));
489 for (unsigned i = 0, e = After.size(); i != e; ++i) {
490 unsigned Start = After[i].first;
491 unsigned End = After[i].second;
492 CurrLI->addRange(LiveRange(Start, End, AValNo));
496 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
497 /// given block, shrink wrap the live interval to the last use (i.e. remove
498 /// from last use to the end of the mbb). In case mbb is the where the barrier
499 /// is, remove from the last use to the barrier.
501 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
502 SmallVector<MachineOperand*, 4> &Uses,
503 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
504 MachineOperand *LastMO = 0;
505 MachineInstr *LastMI = 0;
506 if (MBB != BarrierMBB && Uses.size() == 1) {
507 // Single use, no need to traverse the block. We can't assume this for the
508 // barrier bb though since the use is probably below the barrier.
510 LastMI = LastMO->getParent();
512 MachineBasicBlock::iterator MEE = MBB->begin();
513 MachineBasicBlock::iterator MII;
514 if (MBB == BarrierMBB)
520 MachineInstr *UseMI = &*MII;
521 if (!UseMIs.count(UseMI))
523 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
524 MachineOperand &MO = UseMI->getOperand(i);
525 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
535 // Cut off live range from last use (or beginning of the mbb if there
536 // are no uses in it) to the end of the mbb.
537 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
539 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
540 assert(!LastMO->isKill() && "Last use already terminates the interval?");
543 assert(MBB == BarrierMBB);
544 RangeStart = LIs->getMBBStartIdx(MBB);
546 if (MBB == BarrierMBB)
547 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
548 CurrLI->removeRange(RangeStart, RangeEnd);
550 CurrLI->addKill(ValNo, RangeStart);
552 // Return true if the last use becomes a new kill.
556 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
557 /// chain to find the new 'kills' and shrink wrap the live interval to the
558 /// new kill indices.
560 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
561 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
562 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
563 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
564 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
565 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
566 if (Visited.count(MBB))
569 // If live interval is live in another successor path, then we can't process
570 // this block. But we may able to do so after all the successors have been
572 if (MBB != BarrierMBB) {
573 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
574 SE = MBB->succ_end(); SI != SE; ++SI) {
575 MachineBasicBlock *SMBB = *SI;
578 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
585 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
586 UMII = Uses.find(MBB);
587 if (UMII != Uses.end()) {
588 // At least one use in this mbb, lets look for the kill.
589 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
590 UMII2 = UseMIs.find(MBB);
591 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
592 // Found a kill, shrink wrapping of this path ends here.
594 } else if (MBB == DefMBB) {
595 // There are no uses after the def.
596 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
597 if (UseMBBs.empty()) {
598 // The only use must be below barrier in the barrier block. It's safe to
600 LIs->RemoveMachineInstrFromMaps(DefMI);
601 DefMI->eraseFromParent();
602 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
604 } else if (MBB == BarrierMBB) {
605 // Remove entire live range from start of mbb to barrier.
606 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
607 LIs->getUseIndex(BarrierIdx)+1);
609 // Remove entire live range of the mbb out of the live interval.
610 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
614 // Reached the def mbb, stop traversing this path further.
617 // Traverse the pathes up the predecessor chains further.
618 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
619 PE = MBB->pred_end(); PI != PE; ++PI) {
620 MachineBasicBlock *Pred = *PI;
623 if (Pred == DefMBB && ValNo->hasPHIKill)
624 // Pred is the def bb and the def reaches other val#s, we must
625 // allow the value to be live out of the bb.
627 if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
629 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
630 Uses, UseMIs, UseMBBs);
636 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
638 MachineBasicBlock::iterator RestorePt,
640 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
641 MachineBasicBlock& MBB = *RestorePt->getParent();
643 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
644 unsigned KillIdx = 0;
645 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
646 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
648 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
650 if (KillPt == DefMI->getParent()->end())
653 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
654 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
656 if (KillPt->getParent() == BarrierMBB) {
657 UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
658 LIs->getDefIndex(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 // FIXME: If ValNo->hasPHIKill is false, then renumber the val# by
709 // Remove live range from barrier to the restore. FIXME: Find a better
710 // point to re-start the live interval.
711 UpdateRegisterInterval(ValNo, LIs->getUseIndex(BarrierIdx)+1,
712 LIs->getDefIndex(RestoreIdx));
720 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
721 /// so it would not cross the barrier that's being processed. Shrink wrap
722 /// (minimize) the live interval to the last uses.
723 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
726 // Find live range where current interval cross the barrier.
727 LiveInterval::iterator LR =
728 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
729 VNInfo *ValNo = LR->valno;
731 if (ValNo->def == ~1U) {
732 // Defined by a dead def? How can this be?
733 assert(0 && "Val# is defined by a dead def?");
737 MachineInstr *DefMI = (ValNo->def != ~0U)
738 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
740 // If this would create a new join point, do not split.
741 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
744 // Find all references in the barrier mbb.
745 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
746 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
747 E = MRI->reg_end(); I != E; ++I) {
748 MachineInstr *RefMI = &*I;
749 if (RefMI->getParent() == BarrierMBB)
750 RefsInMBB.insert(RefMI);
753 // Find a point to restore the value after the barrier.
754 unsigned RestoreIndex;
755 MachineBasicBlock::iterator RestorePt =
756 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
757 if (RestorePt == BarrierMBB->end())
760 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
761 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
762 RestoreIndex, RefsInMBB))
765 // Add a spill either before the barrier or after the definition.
766 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
767 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
768 unsigned SpillIndex = 0;
769 MachineInstr *SpillMI = NULL;
771 if (ValNo->def == ~0U) {
772 // If it's defined by a phi, we must split just before the barrier.
773 MachineBasicBlock::iterator SpillPt =
774 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
775 if (SpillPt == BarrierMBB->begin())
776 return false; // No gap to insert spill.
778 SS = CreateSpillStackSlot(CurrLI->reg, RC);
779 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
780 SpillMI = prior(SpillPt);
781 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
782 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
783 RestoreIndex, SpillIndex, SS)) {
784 // If it's already split, just restore the value. There is no need to spill
787 return false; // Def is dead. Do nothing.
788 // Check if it's possible to insert a spill after the def MI.
789 MachineBasicBlock::iterator SpillPt;
790 if (DefMBB == BarrierMBB) {
791 // Add spill after the def and the last use before the barrier.
792 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI, RefsInMBB, SpillIndex);
793 if (SpillPt == DefMBB->begin())
794 return false; // No gap to insert spill.
796 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
797 if (SpillPt == DefMBB->end())
798 return false; // No gap to insert spill.
800 // Add spill. The store instruction kills the register if def is before
801 // the barrier in the barrier block.
802 SS = CreateSpillStackSlot(CurrLI->reg, RC);
803 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
804 DefMBB == BarrierMBB, SS, RC);
805 SpillMI = prior(SpillPt);
806 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
809 // Remember def instruction index to spill index mapping.
810 if (DefMI && SpillMI)
811 Def2SpillMap[ValNo->def] = SpillIndex;
814 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
815 MachineInstr *LoadMI = prior(RestorePt);
816 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
818 // If live interval is spilled in the same block as the barrier, just
819 // create a hole in the interval.
821 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
822 // Update spill stack slot live interval.
823 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
824 LIs->getDefIndex(RestoreIndex));
826 UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
827 LIs->getDefIndex(RestoreIndex));
833 // Update spill stack slot live interval.
834 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
835 LIs->getDefIndex(RestoreIndex));
837 // Shrink wrap the live interval by walking up the CFG and find the
839 // Now let's find all the uses of the val#.
840 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
841 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
842 SmallPtrSet<MachineBasicBlock*, 4> Seen;
843 SmallVector<MachineBasicBlock*, 4> UseMBBs;
844 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
845 UE = MRI->use_end(); UI != UE; ++UI) {
846 MachineOperand &UseMO = UI.getOperand();
847 MachineInstr *UseMI = UseMO.getParent();
848 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
849 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
850 if (ULR->valno != ValNo)
852 MachineBasicBlock *UseMBB = UseMI->getParent();
853 // Remember which other mbb's use this val#.
854 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
855 UseMBBs.push_back(UseMBB);
856 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
857 UMII = Uses.find(UseMBB);
858 if (UMII != Uses.end()) {
859 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
860 UMII2 = UseMIs.find(UseMBB);
861 UMII->second.push_back(&UseMO);
862 UMII2->second.insert(UseMI);
864 SmallVector<MachineOperand*, 4> Ops;
865 Ops.push_back(&UseMO);
866 Uses.insert(std::make_pair(UseMBB, Ops));
867 SmallPtrSet<MachineInstr*, 4> MIs;
869 UseMIs.insert(std::make_pair(UseMBB, MIs));
873 // Walk up the predecessor chains.
874 SmallPtrSet<MachineBasicBlock*, 8> Visited;
875 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMBB, Visited,
876 Uses, UseMIs, UseMBBs);
878 // FIXME: If ValNo->hasPHIKill is false, then renumber the val# by
881 // Remove live range from barrier to the restore. FIXME: Find a better
882 // point to re-start the live interval.
883 UpdateRegisterInterval(ValNo, LIs->getUseIndex(BarrierIdx)+1,
884 LIs->getDefIndex(RestoreIndex));
890 /// SplitRegLiveIntervals - Split all register live intervals that cross the
891 /// barrier that's being processed.
893 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
894 // First find all the virtual registers whose live intervals are intercepted
895 // by the current barrier.
896 SmallVector<LiveInterval*, 8> Intervals;
897 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
898 if (TII->IgnoreRegisterClassBarriers(*RC))
900 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
901 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
902 unsigned Reg = VRs[i];
903 if (!LIs->hasInterval(Reg))
905 LiveInterval *LI = &LIs->getInterval(Reg);
906 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
907 // Virtual register live interval is intercepted by the barrier. We
908 // should split and shrink wrap its interval if possible.
909 Intervals.push_back(LI);
913 // Process the affected live intervals.
915 while (!Intervals.empty()) {
916 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
918 LiveInterval *LI = Intervals.back();
919 Intervals.pop_back();
920 Change |= SplitRegLiveInterval(LI);
926 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
927 MachineBasicBlock* DefMBB,
928 MachineBasicBlock* BarrierMBB) {
929 if (DefMBB == BarrierMBB)
932 if (LR->valno->hasPHIKill)
935 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
936 if (LR->end < MBBEnd)
939 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
940 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
943 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
944 SmallPtrSet<MachineBasicBlock*, 4> Visited;
945 typedef std::pair<MachineBasicBlock*,
946 MachineBasicBlock::succ_iterator> ItPair;
947 SmallVector<ItPair, 4> Stack;
948 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
950 while (!Stack.empty()) {
951 ItPair P = Stack.back();
954 MachineBasicBlock* PredMBB = P.first;
955 MachineBasicBlock::succ_iterator S = P.second;
957 if (S == PredMBB->succ_end())
959 else if (Visited.count(*S)) {
960 Stack.push_back(std::make_pair(PredMBB, ++S));
963 Stack.push_back(std::make_pair(PredMBB, S+1));
965 MachineBasicBlock* MBB = *S;
968 if (MBB == BarrierMBB)
971 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
972 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
973 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
977 else if (MDTN == BarrierMDTN)
979 MDTN = MDTN->getIDom();
982 MBBEnd = LIs->getMBBEndIdx(MBB);
983 if (LR->end > MBBEnd)
984 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
991 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
993 TM = &MF.getTarget();
994 TII = TM->getInstrInfo();
995 MFI = MF.getFrameInfo();
996 MRI = &MF.getRegInfo();
997 LIs = &getAnalysis<LiveIntervals>();
998 LSs = &getAnalysis<LiveStacks>();
1000 bool MadeChange = false;
1002 // Make sure blocks are numbered in order.
1003 MF.RenumberBlocks();
1006 // FIXME: Go top down.
1007 MachineBasicBlock *Entry = MF.begin();
1008 SmallPtrSet<MachineBasicBlock*,16> Visited;
1010 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1011 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1014 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1015 E = BarrierMBB->end(); I != E; ++I) {
1017 const TargetRegisterClass **BarrierRCs =
1018 Barrier->getDesc().getRegClassBarriers();
1021 BarrierIdx = LIs->getInstructionIndex(Barrier);
1022 MadeChange |= SplitRegLiveIntervals(BarrierRCs);
1026 for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
1029 for (MachineBasicBlock::reverse_iterator II = BarrierMBB->rbegin(),
1030 EE = BarrierMBB->rend(); II != EE; ++II) {
1032 const TargetRegisterClass **BarrierRCs =
1033 Barrier->getDesc().getRegClassBarriers();
1036 BarrierIdx = LIs->getInstructionIndex(Barrier);
1037 MadeChange |= SplitRegLiveIntervals(BarrierRCs);