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(NumTotalSplits, "Number of intervals split");
42 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
43 STATISTIC(NumFolds, "Number of intervals split with spill folding");
44 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
45 STATISTIC(NumDeadSpills, "Number of dead spills removed");
48 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
49 MachineFunction *CurrMF;
50 const TargetMachine *TM;
51 const TargetInstrInfo *TII;
52 MachineFrameInfo *MFI;
53 MachineRegisterInfo *MRI;
57 // Barrier - Current barrier being processed.
58 MachineInstr *Barrier;
60 // BarrierMBB - Basic block where the barrier resides in.
61 MachineBasicBlock *BarrierMBB;
63 // Barrier - Current barrier index.
66 // CurrLI - Current live interval being split.
69 // CurrSLI - Current stack slot live interval.
70 LiveInterval *CurrSLI;
72 // CurrSValNo - Current val# for the stack slot live interval.
75 // IntervalSSMap - A map from live interval to spill slots.
76 DenseMap<unsigned, int> IntervalSSMap;
78 // Def2SpillMap - A map from a def instruction index to spill index.
79 DenseMap<unsigned, unsigned> Def2SpillMap;
85 PreAllocSplitting() : MachineFunctionPass(&ID) {}
87 virtual bool runOnMachineFunction(MachineFunction &MF);
89 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
90 AU.addRequired<LiveIntervals>();
91 AU.addPreserved<LiveIntervals>();
92 AU.addRequired<LiveStacks>();
93 AU.addPreserved<LiveStacks>();
94 AU.addPreserved<RegisterCoalescer>();
96 AU.addPreservedID(StrongPHIEliminationID);
98 AU.addPreservedID(PHIEliminationID);
99 AU.addRequired<MachineDominatorTree>();
100 AU.addRequired<MachineLoopInfo>();
101 AU.addPreserved<MachineDominatorTree>();
102 AU.addPreserved<MachineLoopInfo>();
103 MachineFunctionPass::getAnalysisUsage(AU);
106 virtual void releaseMemory() {
107 IntervalSSMap.clear();
108 Def2SpillMap.clear();
111 virtual const char *getPassName() const {
112 return "Pre-Register Allocaton Live Interval Splitting";
115 /// print - Implement the dump method.
116 virtual void print(std::ostream &O, const Module* M = 0) const {
120 void print(std::ostream *O, const Module* M = 0) const {
125 MachineBasicBlock::iterator
126 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
129 MachineBasicBlock::iterator
130 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
131 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
133 MachineBasicBlock::iterator
134 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
135 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
137 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
139 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
140 unsigned&, int&) const;
142 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
144 bool SplitRegLiveInterval(LiveInterval*);
146 bool SplitRegLiveIntervals(const TargetRegisterClass **,
147 SmallPtrSet<LiveInterval*, 8>&);
149 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
150 MachineBasicBlock* BarrierMBB);
151 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
153 MachineBasicBlock::iterator RestorePt,
155 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
156 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
158 MachineInstr* Barrier,
159 MachineBasicBlock* MBB,
161 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
162 void RenumberValno(VNInfo* VN);
163 void ReconstructLiveInterval(LiveInterval* LI);
164 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
165 unsigned getNumberOfSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
166 unsigned Reg, int FrameIndex);
167 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator use,
168 MachineBasicBlock* MBB,
170 SmallPtrSet<MachineInstr*, 4>& Visited,
171 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
172 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
173 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
174 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
175 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
176 bool toplevel, bool intrablock);
178 } // end anonymous namespace
180 char PreAllocSplitting::ID = 0;
182 static RegisterPass<PreAllocSplitting>
183 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
185 const PassInfo *const llvm::PreAllocSplittingID = &X;
188 /// findNextEmptySlot - Find a gap after the given machine instruction in the
189 /// instruction index map. If there isn't one, return end().
190 MachineBasicBlock::iterator
191 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
192 unsigned &SpotIndex) {
193 MachineBasicBlock::iterator MII = MI;
194 if (++MII != MBB->end()) {
195 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
204 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
205 /// for spilling the current live interval. The index must be before any
206 /// defs and uses of the live interval register in the mbb. Return begin() if
208 MachineBasicBlock::iterator
209 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
211 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
212 unsigned &SpillIndex) {
213 MachineBasicBlock::iterator Pt = MBB->begin();
215 // Go top down if RefsInMBB is empty.
216 if (RefsInMBB.empty() && !DefMI) {
217 MachineBasicBlock::iterator MII = MBB->begin();
218 MachineBasicBlock::iterator EndPt = MI;
221 unsigned Index = LIs->getInstructionIndex(MII);
222 unsigned Gap = LIs->findGapBeforeInstr(Index);
228 } while (MII != EndPt);
230 MachineBasicBlock::iterator MII = MI;
231 MachineBasicBlock::iterator EndPt = DefMI
232 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
233 while (MII != EndPt && !RefsInMBB.count(MII)) {
234 unsigned Index = LIs->getInstructionIndex(MII);
235 if (LIs->hasGapBeforeInstr(Index)) {
237 SpillIndex = LIs->findGapBeforeInstr(Index, true);
246 /// findRestorePoint - Find a gap in the instruction index map that's suitable
247 /// for restoring the current live interval value. The index must be before any
248 /// uses of the live interval register in the mbb. Return end() if none is
250 MachineBasicBlock::iterator
251 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
253 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
254 unsigned &RestoreIndex) {
255 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
256 // begin index accordingly.
257 MachineBasicBlock::iterator Pt = MBB->end();
258 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
260 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
261 // the last index in the live range.
262 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
263 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
264 MachineBasicBlock::iterator EndPt = MI;
267 unsigned Index = LIs->getInstructionIndex(MII);
268 unsigned Gap = LIs->findGapBeforeInstr(Index);
275 } while (MII != EndPt);
277 MachineBasicBlock::iterator MII = MI;
279 // FIXME: Limit the number of instructions to examine to reduce
281 while (MII != MBB->end()) {
282 unsigned Index = LIs->getInstructionIndex(MII);
285 unsigned Gap = LIs->findGapBeforeInstr(Index);
290 if (RefsInMBB.count(MII))
299 /// CreateSpillStackSlot - Create a stack slot for the live interval being
300 /// split. If the live interval was previously split, just reuse the same
302 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
303 const TargetRegisterClass *RC) {
305 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
306 if (I != IntervalSSMap.end()) {
309 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
310 IntervalSSMap[Reg] = SS;
313 // Create live interval for stack slot.
314 CurrSLI = &LSs->getOrCreateInterval(SS);
315 if (CurrSLI->hasAtLeastOneValue())
316 CurrSValNo = CurrSLI->getValNumInfo(0);
318 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
322 /// IsAvailableInStack - Return true if register is available in a split stack
323 /// slot at the specified index.
325 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
326 unsigned Reg, unsigned DefIndex,
327 unsigned RestoreIndex, unsigned &SpillIndex,
332 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
333 if (I == IntervalSSMap.end())
335 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
336 if (II == Def2SpillMap.end())
339 // If last spill of def is in the same mbb as barrier mbb (where restore will
340 // be), make sure it's not below the intended restore index.
341 // FIXME: Undo the previous spill?
342 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
343 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
347 SpillIndex = II->second;
351 /// UpdateSpillSlotInterval - Given the specified val# of the register live
352 /// interval being split, and the spill and restore indicies, update the live
353 /// interval of the spill stack slot.
355 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
356 unsigned RestoreIndex) {
357 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
358 "Expect restore in the barrier mbb");
360 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
361 if (MBB == BarrierMBB) {
362 // Intra-block spill + restore. We are done.
363 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
364 CurrSLI->addRange(SLR);
368 SmallPtrSet<MachineBasicBlock*, 4> Processed;
369 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
370 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
371 CurrSLI->addRange(SLR);
372 Processed.insert(MBB);
374 // Start from the spill mbb, figure out the extend of the spill slot's
376 SmallVector<MachineBasicBlock*, 4> WorkList;
377 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
378 if (LR->end > EndIdx)
379 // If live range extend beyond end of mbb, add successors to work list.
380 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
381 SE = MBB->succ_end(); SI != SE; ++SI)
382 WorkList.push_back(*SI);
384 while (!WorkList.empty()) {
385 MachineBasicBlock *MBB = WorkList.back();
387 if (Processed.count(MBB))
389 unsigned Idx = LIs->getMBBStartIdx(MBB);
390 LR = CurrLI->getLiveRangeContaining(Idx);
391 if (LR && LR->valno == ValNo) {
392 EndIdx = LIs->getMBBEndIdx(MBB);
393 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
394 // Spill slot live interval stops at the restore.
395 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
396 CurrSLI->addRange(SLR);
397 } else if (LR->end > EndIdx) {
398 // Live range extends beyond end of mbb, process successors.
399 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
400 CurrSLI->addRange(SLR);
401 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
402 SE = MBB->succ_end(); SI != SE; ++SI)
403 WorkList.push_back(*SI);
405 LiveRange SLR(Idx, LR->end, CurrSValNo);
406 CurrSLI->addRange(SLR);
408 Processed.insert(MBB);
413 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
414 /// construction algorithm to compute the ranges and valnos for an interval.
415 VNInfo* PreAllocSplitting::PerformPHIConstruction(
416 MachineBasicBlock::iterator use,
417 MachineBasicBlock* MBB,
419 SmallPtrSet<MachineInstr*, 4>& Visited,
420 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
421 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
422 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
423 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
424 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
425 bool toplevel, bool intrablock) {
426 // Return memoized result if it's available.
427 if (toplevel && Visited.count(use) && NewVNs.count(use))
429 else if (!toplevel && intrablock && NewVNs.count(use))
431 else if (!intrablock && LiveOut.count(MBB))
434 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
436 // Check if our block contains any uses or defs.
437 bool ContainsDefs = Defs.count(MBB);
438 bool ContainsUses = Uses.count(MBB);
442 // Enumerate the cases of use/def contaning blocks.
443 if (!ContainsDefs && !ContainsUses) {
445 // NOTE: Because this is the fallback case from other cases, we do NOT
446 // assume that we are not intrablock here.
447 if (Phis.count(MBB)) return Phis[MBB];
449 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
451 if (MBB->pred_size() == 1) {
452 Phis[MBB] = ret = PerformPHIConstruction((*MBB->pred_begin())->end(),
453 *(MBB->pred_begin()), LI, Visited,
454 Defs, Uses, NewVNs, LiveOut, Phis,
456 unsigned EndIndex = 0;
458 EndIndex = LIs->getInstructionIndex(use);
459 EndIndex = LiveIntervals::getUseIndex(EndIndex);
461 EndIndex = LIs->getMBBEndIdx(MBB);
463 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
465 LI->addKill(ret, EndIndex);
467 Phis[MBB] = ret = LI->getNextValue(~0U, /*FIXME*/ 0,
468 LIs->getVNInfoAllocator());
469 if (!intrablock) LiveOut[MBB] = ret;
471 // If there are no uses or defs between our starting point and the
472 // beginning of the block, then recursive perform phi construction
473 // on our predecessors.
474 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
475 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
476 PE = MBB->pred_end(); PI != PE; ++PI) {
477 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
478 Visited, Defs, Uses, NewVNs,
479 LiveOut, Phis, false, false);
481 IncomingVNs[*PI] = Incoming;
484 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
485 // VNInfo to represent the joined value.
486 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
487 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
488 I->second->hasPHIKill = true;
489 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
490 LI->addKill(I->second, KillIndex);
493 unsigned EndIndex = 0;
495 EndIndex = LIs->getInstructionIndex(use);
496 EndIndex = LiveIntervals::getUseIndex(EndIndex);
498 EndIndex = LIs->getMBBEndIdx(MBB);
499 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
501 LI->addKill(ret, EndIndex);
503 } else if (ContainsDefs && !ContainsUses) {
504 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
506 // Search for the def in this block. If we don't find it before the
507 // instruction we care about, go to the fallback case. Note that that
508 // should never happen: this cannot be intrablock, so use should
509 // always be an end() iterator.
510 assert(use == MBB->end() && "No use marked in intrablock");
512 MachineBasicBlock::iterator walker = use;
514 while (walker != MBB->begin())
515 if (BlockDefs.count(walker)) {
520 // Once we've found it, extend its VNInfo to our instruction.
521 unsigned DefIndex = LIs->getInstructionIndex(walker);
522 DefIndex = LiveIntervals::getDefIndex(DefIndex);
523 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
525 ret = NewVNs[walker];
526 LI->addRange(LiveRange(DefIndex, EndIndex+1, ret));
527 } else if (!ContainsDefs && ContainsUses) {
528 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
530 // Search for the use in this block that precedes the instruction we care
531 // about, going to the fallback case if we don't find it.
533 if (use == MBB->begin())
536 MachineBasicBlock::iterator walker = use;
539 while (walker != MBB->begin())
540 if (BlockUses.count(walker)) {
546 // Must check begin() too.
548 if (BlockUses.count(walker))
554 unsigned UseIndex = LIs->getInstructionIndex(walker);
555 UseIndex = LiveIntervals::getUseIndex(UseIndex);
556 unsigned EndIndex = 0;
558 EndIndex = LIs->getInstructionIndex(use);
559 EndIndex = LiveIntervals::getUseIndex(EndIndex);
561 EndIndex = LIs->getMBBEndIdx(MBB);
563 // Now, recursively phi construct the VNInfo for the use we found,
564 // and then extend it to include the instruction we care about
565 ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
566 NewVNs, LiveOut, Phis, false, true);
568 LI->addRange(LiveRange(UseIndex, EndIndex+1, ret));
570 // FIXME: Need to set kills properly for inter-block stuff.
571 if (LI->isKill(ret, UseIndex)) LI->removeKill(ret, UseIndex);
573 LI->addKill(ret, EndIndex);
574 } else if (ContainsDefs && ContainsUses){
575 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
576 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
578 // This case is basically a merging of the two preceding case, with the
579 // special note that checking for defs must take precedence over checking
580 // for uses, because of two-address instructions.
582 if (use == MBB->begin())
585 MachineBasicBlock::iterator walker = use;
587 bool foundDef = false;
588 bool foundUse = false;
589 while (walker != MBB->begin())
590 if (BlockDefs.count(walker)) {
593 } else if (BlockUses.count(walker)) {
599 // Must check begin() too.
600 if (!foundDef && !foundUse) {
601 if (BlockDefs.count(walker))
603 else if (BlockUses.count(walker))
609 unsigned StartIndex = LIs->getInstructionIndex(walker);
610 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
611 LiveIntervals::getUseIndex(StartIndex);
612 unsigned EndIndex = 0;
614 EndIndex = LIs->getInstructionIndex(use);
615 EndIndex = LiveIntervals::getUseIndex(EndIndex);
617 EndIndex = LIs->getMBBEndIdx(MBB);
620 ret = NewVNs[walker];
622 ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
623 NewVNs, LiveOut, Phis, false, true);
625 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
627 if (foundUse && LI->isKill(ret, StartIndex))
628 LI->removeKill(ret, StartIndex);
630 LI->addKill(ret, EndIndex);
634 // Memoize results so we don't have to recompute them.
635 if (!intrablock) LiveOut[MBB] = ret;
637 if (!NewVNs.count(use))
645 /// ReconstructLiveInterval - Recompute a live interval from scratch.
646 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
647 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
649 // Clear the old ranges and valnos;
652 // Cache the uses and defs of the register
653 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
656 // Keep track of the new VNs we're creating.
657 DenseMap<MachineInstr*, VNInfo*> NewVNs;
658 SmallPtrSet<VNInfo*, 2> PhiVNs;
660 // Cache defs, and create a new VNInfo for each def.
661 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
662 DE = MRI->def_end(); DI != DE; ++DI) {
663 Defs[(*DI).getParent()].insert(&*DI);
665 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
666 DefIdx = LiveIntervals::getDefIndex(DefIdx);
668 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
670 // If the def is a move, set the copy field.
671 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
672 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
673 if (DstReg == LI->reg)
676 NewVNs[&*DI] = NewVN;
679 // Cache uses as a separate pass from actually processing them.
680 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
681 UE = MRI->use_end(); UI != UE; ++UI)
682 Uses[(*UI).getParent()].insert(&*UI);
684 // Now, actually process every use and use a phi construction algorithm
685 // to walk from it to its reaching definitions, building VNInfos along
687 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
688 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
689 SmallPtrSet<MachineInstr*, 4> Visited;
690 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
691 UE = MRI->use_end(); UI != UE; ++UI) {
692 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
693 Uses, NewVNs, LiveOut, Phis, true, true);
696 // Add ranges for dead defs
697 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
698 DE = MRI->def_end(); DI != DE; ++DI) {
699 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
700 DefIdx = LiveIntervals::getDefIndex(DefIdx);
702 if (LI->liveAt(DefIdx)) continue;
704 VNInfo* DeadVN = NewVNs[&*DI];
705 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
706 LI->addKill(DeadVN, DefIdx);
710 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
711 /// be allocated to a different register. This function creates a new vreg,
712 /// copies the valno and its live ranges over to the new vreg's interval,
713 /// removes them from the old interval, and rewrites all uses and defs of
714 /// the original reg to the new vreg within those ranges.
715 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
716 SmallVector<VNInfo*, 4> Stack;
717 SmallVector<VNInfo*, 4> VNsToCopy;
720 // Walk through and copy the valno we care about, and any other valnos
721 // that are two-address redefinitions of the one we care about. These
722 // will need to be rewritten as well. We also check for safety of the
723 // renumbering here, by making sure that none of the valno involved has
725 while (!Stack.empty()) {
726 VNInfo* OldVN = Stack.back();
729 // Bail out if we ever encounter a valno that has a PHI kill. We can't
731 if (OldVN->hasPHIKill) return;
733 VNsToCopy.push_back(OldVN);
735 // Locate two-address redefinitions
736 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
737 KE = OldVN->kills.end(); KI != KE; ++KI) {
738 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
739 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
740 if (DefIdx == ~0U) continue;
741 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
743 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
744 if (NextVN == OldVN) continue;
745 Stack.push_back(NextVN);
750 // Create the new vreg
751 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
753 // Create the new live interval
754 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
756 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
757 VNsToCopy.end(); OI != OE; ++OI) {
760 // Copy the valno over
761 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
762 LIs->getVNInfoAllocator());
763 NewLI.copyValNumInfo(NewVN, OldVN);
764 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
766 // Remove the valno from the old interval
767 CurrLI->removeValNo(OldVN);
770 // Rewrite defs and uses. This is done in two stages to avoid invalidating
772 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
774 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
775 E = MRI->reg_end(); I != E; ++I) {
776 MachineOperand& MO = I.getOperand();
777 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
779 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
780 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
781 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
784 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
785 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
786 MachineInstr* Inst = I->first;
787 unsigned OpIdx = I->second;
788 MachineOperand& MO = Inst->getOperand(OpIdx);
795 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
797 MachineBasicBlock::iterator RestorePt,
799 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
800 MachineBasicBlock& MBB = *RestorePt->getParent();
802 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
803 unsigned KillIdx = 0;
804 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
805 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
807 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
809 if (KillPt == DefMI->getParent()->end())
812 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
813 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
815 ReconstructLiveInterval(CurrLI);
816 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
817 RematIdx = LiveIntervals::getDefIndex(RematIdx);
818 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
825 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
826 const TargetRegisterClass* RC,
828 MachineInstr* Barrier,
829 MachineBasicBlock* MBB,
831 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
832 MachineBasicBlock::iterator Pt = MBB->begin();
834 // Go top down if RefsInMBB is empty.
835 if (RefsInMBB.empty())
838 MachineBasicBlock::iterator FoldPt = Barrier;
839 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
840 !RefsInMBB.count(FoldPt))
843 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
847 SmallVector<unsigned, 1> Ops;
848 Ops.push_back(OpIdx);
850 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
853 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
854 if (I != IntervalSSMap.end()) {
857 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
861 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
865 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
866 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
869 IntervalSSMap[vreg] = SS;
870 CurrSLI = &LSs->getOrCreateInterval(SS);
871 if (CurrSLI->hasAtLeastOneValue())
872 CurrSValNo = CurrSLI->getValNumInfo(0);
874 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
880 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
881 /// so it would not cross the barrier that's being processed. Shrink wrap
882 /// (minimize) the live interval to the last uses.
883 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
886 // Find live range where current interval cross the barrier.
887 LiveInterval::iterator LR =
888 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
889 VNInfo *ValNo = LR->valno;
891 if (ValNo->def == ~1U) {
892 // Defined by a dead def? How can this be?
893 assert(0 && "Val# is defined by a dead def?");
897 MachineInstr *DefMI = (ValNo->def != ~0U)
898 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
900 // If this would create a new join point, do not split.
901 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
904 // Find all references in the barrier mbb.
905 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
906 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
907 E = MRI->reg_end(); I != E; ++I) {
908 MachineInstr *RefMI = &*I;
909 if (RefMI->getParent() == BarrierMBB)
910 RefsInMBB.insert(RefMI);
913 // Find a point to restore the value after the barrier.
914 unsigned RestoreIndex = 0;
915 MachineBasicBlock::iterator RestorePt =
916 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
917 if (RestorePt == BarrierMBB->end())
920 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
921 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
922 RestoreIndex, RefsInMBB))
925 // Add a spill either before the barrier or after the definition.
926 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
927 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
928 unsigned SpillIndex = 0;
929 MachineInstr *SpillMI = NULL;
931 if (ValNo->def == ~0U) {
932 // If it's defined by a phi, we must split just before the barrier.
933 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
934 BarrierMBB, SS, RefsInMBB))) {
935 SpillIndex = LIs->getInstructionIndex(SpillMI);
937 MachineBasicBlock::iterator SpillPt =
938 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
939 if (SpillPt == BarrierMBB->begin())
940 return false; // No gap to insert spill.
943 SS = CreateSpillStackSlot(CurrLI->reg, RC);
944 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
945 SpillMI = prior(SpillPt);
946 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
948 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
949 RestoreIndex, SpillIndex, SS)) {
950 // If it's already split, just restore the value. There is no need to spill
953 return false; // Def is dead. Do nothing.
955 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
956 BarrierMBB, SS, RefsInMBB))) {
957 SpillIndex = LIs->getInstructionIndex(SpillMI);
959 // Check if it's possible to insert a spill after the def MI.
960 MachineBasicBlock::iterator SpillPt;
961 if (DefMBB == BarrierMBB) {
962 // Add spill after the def and the last use before the barrier.
963 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
964 RefsInMBB, SpillIndex);
965 if (SpillPt == DefMBB->begin())
966 return false; // No gap to insert spill.
968 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
969 if (SpillPt == DefMBB->end())
970 return false; // No gap to insert spill.
972 // Add spill. The store instruction kills the register if def is before
973 // the barrier in the barrier block.
974 SS = CreateSpillStackSlot(CurrLI->reg, RC);
975 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
976 DefMBB == BarrierMBB, SS, RC);
977 SpillMI = prior(SpillPt);
978 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
982 // Remember def instruction index to spill index mapping.
983 if (DefMI && SpillMI)
984 Def2SpillMap[ValNo->def] = SpillIndex;
987 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
988 MachineInstr *LoadMI = prior(RestorePt);
989 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
991 // Update spill stack slot live interval.
992 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
993 LIs->getDefIndex(RestoreIndex));
995 ReconstructLiveInterval(CurrLI);
996 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
997 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
998 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1004 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1005 /// barrier that's being processed.
1007 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1008 SmallPtrSet<LiveInterval*, 8>& Split) {
1009 // First find all the virtual registers whose live intervals are intercepted
1010 // by the current barrier.
1011 SmallVector<LiveInterval*, 8> Intervals;
1012 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1013 if (TII->IgnoreRegisterClassBarriers(*RC))
1015 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1016 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1017 unsigned Reg = VRs[i];
1018 if (!LIs->hasInterval(Reg))
1020 LiveInterval *LI = &LIs->getInterval(Reg);
1021 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1022 // Virtual register live interval is intercepted by the barrier. We
1023 // should split and shrink wrap its interval if possible.
1024 Intervals.push_back(LI);
1028 // Process the affected live intervals.
1029 bool Change = false;
1030 while (!Intervals.empty()) {
1031 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1033 else if (NumSplits == 4)
1035 LiveInterval *LI = Intervals.back();
1036 Intervals.pop_back();
1037 bool result = SplitRegLiveInterval(LI);
1038 if (result) Split.insert(LI);
1045 unsigned PreAllocSplitting::getNumberOfSpills(
1046 SmallPtrSet<MachineInstr*, 4>& MIs,
1047 unsigned Reg, int FrameIndex) {
1048 unsigned Spills = 0;
1049 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1051 int StoreFrameIndex;
1052 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1053 if (StoreVReg == Reg && StoreFrameIndex == FrameIndex)
1060 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1061 /// split, and see if any of the spills are unnecessary. If so, remove them.
1062 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1063 bool changed = false;
1065 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1066 LE = split.end(); LI != LE; ++LI) {
1067 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1069 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1070 UE = MRI->use_end(); UI != UE; ++UI) {
1071 unsigned index = LIs->getInstructionIndex(&*UI);
1072 index = LiveIntervals::getUseIndex(index);
1074 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1075 VNUseCount[LR->valno].insert(&*UI);
1078 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1079 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1080 VNInfo* CurrVN = *VI;
1081 if (CurrVN->hasPHIKill) continue;
1083 unsigned DefIdx = CurrVN->def;
1084 if (DefIdx == ~0U || DefIdx == ~1U) continue;
1086 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1088 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1090 if (VNUseCount[CurrVN].size() == 0) {
1091 LIs->RemoveMachineInstrFromMaps(DefMI);
1092 (*LI)->removeValNo(CurrVN);
1093 DefMI->eraseFromParent();
1099 unsigned SpillCount = getNumberOfSpills(VNUseCount[CurrVN],
1100 (*LI)->reg, FrameIndex);
1101 if (SpillCount != VNUseCount[CurrVN].size()) continue;
1103 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1104 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1106 LIs->RemoveMachineInstrFromMaps(*UI);
1107 (*UI)->eraseFromParent();
1110 LIs->RemoveMachineInstrFromMaps(DefMI);
1111 (*LI)->removeValNo(CurrVN);
1112 DefMI->eraseFromParent();
1121 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1122 MachineBasicBlock* DefMBB,
1123 MachineBasicBlock* BarrierMBB) {
1124 if (DefMBB == BarrierMBB)
1127 if (LR->valno->hasPHIKill)
1130 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1131 if (LR->end < MBBEnd)
1134 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1135 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1138 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1139 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1140 typedef std::pair<MachineBasicBlock*,
1141 MachineBasicBlock::succ_iterator> ItPair;
1142 SmallVector<ItPair, 4> Stack;
1143 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1145 while (!Stack.empty()) {
1146 ItPair P = Stack.back();
1149 MachineBasicBlock* PredMBB = P.first;
1150 MachineBasicBlock::succ_iterator S = P.second;
1152 if (S == PredMBB->succ_end())
1154 else if (Visited.count(*S)) {
1155 Stack.push_back(std::make_pair(PredMBB, ++S));
1158 Stack.push_back(std::make_pair(PredMBB, S+1));
1160 MachineBasicBlock* MBB = *S;
1161 Visited.insert(MBB);
1163 if (MBB == BarrierMBB)
1166 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1167 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1168 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1170 if (MDTN == DefMDTN)
1172 else if (MDTN == BarrierMDTN)
1174 MDTN = MDTN->getIDom();
1177 MBBEnd = LIs->getMBBEndIdx(MBB);
1178 if (LR->end > MBBEnd)
1179 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1186 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1188 TM = &MF.getTarget();
1189 TII = TM->getInstrInfo();
1190 MFI = MF.getFrameInfo();
1191 MRI = &MF.getRegInfo();
1192 LIs = &getAnalysis<LiveIntervals>();
1193 LSs = &getAnalysis<LiveStacks>();
1195 bool MadeChange = false;
1198 // Make sure blocks are numbered in order.
1199 MF.RenumberBlocks();
1201 MachineBasicBlock *Entry = MF.begin();
1202 SmallPtrSet<MachineBasicBlock*,16> Visited;
1204 SmallPtrSet<LiveInterval*, 8> Split;
1206 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1207 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1210 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1211 E = BarrierMBB->end(); I != E; ++I) {
1213 const TargetRegisterClass **BarrierRCs =
1214 Barrier->getDesc().getRegClassBarriers();
1217 BarrierIdx = LIs->getInstructionIndex(Barrier);
1218 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1222 MadeChange |= removeDeadSpills(Split);
1225 NumTotalSplits += NumSplits;