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);
40 static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1), cl::Hidden);
42 STATISTIC(NumSplits, "Number of intervals split");
43 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
44 STATISTIC(NumFolds, "Number of intervals split with spill folding");
45 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
46 STATISTIC(NumDeadSpills, "Number of dead spills removed");
49 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
50 MachineFunction *CurrMF;
51 const TargetMachine *TM;
52 const TargetInstrInfo *TII;
53 const TargetRegisterInfo* TRI;
54 MachineFrameInfo *MFI;
55 MachineRegisterInfo *MRI;
59 // Barrier - Current barrier being processed.
60 MachineInstr *Barrier;
62 // BarrierMBB - Basic block where the barrier resides in.
63 MachineBasicBlock *BarrierMBB;
65 // Barrier - Current barrier index.
68 // CurrLI - Current live interval being split.
71 // CurrSLI - Current stack slot live interval.
72 LiveInterval *CurrSLI;
74 // CurrSValNo - Current val# for the stack slot live interval.
77 // IntervalSSMap - A map from live interval to spill slots.
78 DenseMap<unsigned, int> IntervalSSMap;
80 // Def2SpillMap - A map from a def instruction index to spill index.
81 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 getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
166 unsigned Reg, int FrameIndex, bool& TwoAddr);
167 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
168 MachineBasicBlock* MBB, LiveInterval* LI,
169 SmallPtrSet<MachineInstr*, 4>& Visited,
170 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
171 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
172 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
173 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
174 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
175 bool IsTopLevel, bool IsIntraBlock);
176 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
177 MachineBasicBlock* MBB, LiveInterval* LI,
178 SmallPtrSet<MachineInstr*, 4>& Visited,
179 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
180 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
181 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
182 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
183 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
184 bool IsTopLevel, bool IsIntraBlock);
186 } // end anonymous namespace
188 char PreAllocSplitting::ID = 0;
190 static RegisterPass<PreAllocSplitting>
191 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
193 const PassInfo *const llvm::PreAllocSplittingID = &X;
196 /// findNextEmptySlot - Find a gap after the given machine instruction in the
197 /// instruction index map. If there isn't one, return end().
198 MachineBasicBlock::iterator
199 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
200 unsigned &SpotIndex) {
201 MachineBasicBlock::iterator MII = MI;
202 if (++MII != MBB->end()) {
203 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
212 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
213 /// for spilling the current live interval. The index must be before any
214 /// defs and uses of the live interval register in the mbb. Return begin() if
216 MachineBasicBlock::iterator
217 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
219 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
220 unsigned &SpillIndex) {
221 MachineBasicBlock::iterator Pt = MBB->begin();
223 // Go top down if RefsInMBB is empty.
224 if (RefsInMBB.empty() && !DefMI) {
225 MachineBasicBlock::iterator MII = MBB->begin();
226 MachineBasicBlock::iterator EndPt = MI;
228 if (MII == EndPt) return Pt;
232 unsigned Index = LIs->getInstructionIndex(MII);
233 unsigned Gap = LIs->findGapBeforeInstr(Index);
235 // We can't insert the spill between the barrier (a call), and its
236 // corresponding call frame setup/teardown.
237 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
238 bool reachedBarrier = false;
241 reachedBarrier = true;
245 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
247 if (reachedBarrier) break;
253 } while (MII != EndPt);
255 MachineBasicBlock::iterator MII = MI;
256 MachineBasicBlock::iterator EndPt = DefMI
257 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
259 while (MII != EndPt && !RefsInMBB.count(MII)) {
260 unsigned Index = LIs->getInstructionIndex(MII);
262 // We can't insert the spill between the barrier (a call), and its
263 // corresponding call frame setup.
264 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
267 } if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
268 bool reachedBarrier = false;
269 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
272 reachedBarrier = true;
277 if (reachedBarrier) break;
279 } else if (LIs->hasGapBeforeInstr(Index)) {
281 SpillIndex = LIs->findGapBeforeInstr(Index, true);
290 /// findRestorePoint - Find a gap in the instruction index map that's suitable
291 /// for restoring the current live interval value. The index must be before any
292 /// uses of the live interval register in the mbb. Return end() if none is
294 MachineBasicBlock::iterator
295 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
297 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
298 unsigned &RestoreIndex) {
299 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
300 // begin index accordingly.
301 MachineBasicBlock::iterator Pt = MBB->end();
302 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
304 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
305 // the last index in the live range.
306 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
307 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
308 MachineBasicBlock::iterator EndPt = MI;
310 if (MII == EndPt) return Pt;
314 unsigned Index = LIs->getInstructionIndex(MII);
315 unsigned Gap = LIs->findGapBeforeInstr(Index);
317 // We can't insert a restore between the barrier (a call) and its
318 // corresponding call frame teardown.
319 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
320 bool reachedBarrier = false;
321 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
324 reachedBarrier = true;
329 if (reachedBarrier) break;
338 } while (MII != EndPt);
340 MachineBasicBlock::iterator MII = MI;
343 // FIXME: Limit the number of instructions to examine to reduce
345 while (MII != MBB->getFirstTerminator()) {
346 unsigned Index = LIs->getInstructionIndex(MII);
349 unsigned Gap = LIs->findGapBeforeInstr(Index);
351 // We can't insert a restore between the barrier (a call) and its
352 // corresponding call frame teardown.
353 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
356 } else if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
357 bool reachedBarrier = false;
359 if (MII == MBB->getFirstTerminator() || RefsInMBB.count(MII)) {
360 reachedBarrier = true;
365 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
367 if (reachedBarrier) break;
373 if (RefsInMBB.count(MII))
382 /// CreateSpillStackSlot - Create a stack slot for the live interval being
383 /// split. If the live interval was previously split, just reuse the same
385 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
386 const TargetRegisterClass *RC) {
388 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
389 if (I != IntervalSSMap.end()) {
392 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
393 IntervalSSMap[Reg] = SS;
396 // Create live interval for stack slot.
397 CurrSLI = &LSs->getOrCreateInterval(SS);
398 if (CurrSLI->hasAtLeastOneValue())
399 CurrSValNo = CurrSLI->getValNumInfo(0);
401 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
405 /// IsAvailableInStack - Return true if register is available in a split stack
406 /// slot at the specified index.
408 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
409 unsigned Reg, unsigned DefIndex,
410 unsigned RestoreIndex, unsigned &SpillIndex,
415 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
416 if (I == IntervalSSMap.end())
418 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
419 if (II == Def2SpillMap.end())
422 // If last spill of def is in the same mbb as barrier mbb (where restore will
423 // be), make sure it's not below the intended restore index.
424 // FIXME: Undo the previous spill?
425 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
426 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
430 SpillIndex = II->second;
434 /// UpdateSpillSlotInterval - Given the specified val# of the register live
435 /// interval being split, and the spill and restore indicies, update the live
436 /// interval of the spill stack slot.
438 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
439 unsigned RestoreIndex) {
440 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
441 "Expect restore in the barrier mbb");
443 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
444 if (MBB == BarrierMBB) {
445 // Intra-block spill + restore. We are done.
446 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
447 CurrSLI->addRange(SLR);
451 SmallPtrSet<MachineBasicBlock*, 4> Processed;
452 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
453 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
454 CurrSLI->addRange(SLR);
455 Processed.insert(MBB);
457 // Start from the spill mbb, figure out the extend of the spill slot's
459 SmallVector<MachineBasicBlock*, 4> WorkList;
460 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
461 if (LR->end > EndIdx)
462 // If live range extend beyond end of mbb, add successors to work list.
463 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
464 SE = MBB->succ_end(); SI != SE; ++SI)
465 WorkList.push_back(*SI);
467 while (!WorkList.empty()) {
468 MachineBasicBlock *MBB = WorkList.back();
470 if (Processed.count(MBB))
472 unsigned Idx = LIs->getMBBStartIdx(MBB);
473 LR = CurrLI->getLiveRangeContaining(Idx);
474 if (LR && LR->valno == ValNo) {
475 EndIdx = LIs->getMBBEndIdx(MBB);
476 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
477 // Spill slot live interval stops at the restore.
478 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
479 CurrSLI->addRange(SLR);
480 } else if (LR->end > EndIdx) {
481 // Live range extends beyond end of mbb, process successors.
482 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
483 CurrSLI->addRange(SLR);
484 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
485 SE = MBB->succ_end(); SI != SE; ++SI)
486 WorkList.push_back(*SI);
488 LiveRange SLR(Idx, LR->end, CurrSValNo);
489 CurrSLI->addRange(SLR);
491 Processed.insert(MBB);
496 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
497 /// construction algorithm to compute the ranges and valnos for an interval.
499 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
500 MachineBasicBlock* MBB, LiveInterval* LI,
501 SmallPtrSet<MachineInstr*, 4>& Visited,
502 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
503 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
504 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
505 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
506 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
507 bool IsTopLevel, bool IsIntraBlock) {
508 // Return memoized result if it's available.
509 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
511 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
513 else if (!IsIntraBlock && LiveOut.count(MBB))
516 // Check if our block contains any uses or defs.
517 bool ContainsDefs = Defs.count(MBB);
518 bool ContainsUses = Uses.count(MBB);
522 // Enumerate the cases of use/def contaning blocks.
523 if (!ContainsDefs && !ContainsUses) {
524 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
525 NewVNs, LiveOut, Phis,
526 IsTopLevel, IsIntraBlock);
527 } else if (ContainsDefs && !ContainsUses) {
528 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
530 // Search for the def in this block. If we don't find it before the
531 // instruction we care about, go to the fallback case. Note that that
532 // should never happen: this cannot be intrablock, so use should
533 // always be an end() iterator.
534 assert(UseI == MBB->end() && "No use marked in intrablock");
536 MachineBasicBlock::iterator Walker = UseI;
538 while (Walker != MBB->begin()) {
539 if (BlockDefs.count(Walker))
544 // Once we've found it, extend its VNInfo to our instruction.
545 unsigned DefIndex = LIs->getInstructionIndex(Walker);
546 DefIndex = LiveIntervals::getDefIndex(DefIndex);
547 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
549 RetVNI = NewVNs[Walker];
550 LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
551 } else if (!ContainsDefs && ContainsUses) {
552 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
554 // Search for the use in this block that precedes the instruction we care
555 // about, going to the fallback case if we don't find it.
556 if (UseI == MBB->begin())
557 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
558 Uses, NewVNs, LiveOut, Phis,
559 IsTopLevel, IsIntraBlock);
561 MachineBasicBlock::iterator Walker = UseI;
564 while (Walker != MBB->begin()) {
565 if (BlockUses.count(Walker)) {
572 // Must check begin() too.
574 if (BlockUses.count(Walker))
577 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
578 Uses, NewVNs, LiveOut, Phis,
579 IsTopLevel, IsIntraBlock);
582 unsigned UseIndex = LIs->getInstructionIndex(Walker);
583 UseIndex = LiveIntervals::getUseIndex(UseIndex);
584 unsigned EndIndex = 0;
586 EndIndex = LIs->getInstructionIndex(UseI);
587 EndIndex = LiveIntervals::getUseIndex(EndIndex);
589 EndIndex = LIs->getMBBEndIdx(MBB);
591 // Now, recursively phi construct the VNInfo for the use we found,
592 // and then extend it to include the instruction we care about
593 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
594 NewVNs, LiveOut, Phis, false, true);
596 LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
598 // FIXME: Need to set kills properly for inter-block stuff.
599 if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
601 LI->addKill(RetVNI, EndIndex);
602 } else if (ContainsDefs && ContainsUses) {
603 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
604 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
606 // This case is basically a merging of the two preceding case, with the
607 // special note that checking for defs must take precedence over checking
608 // for uses, because of two-address instructions.
610 if (UseI == MBB->begin())
611 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
612 NewVNs, LiveOut, Phis,
613 IsTopLevel, IsIntraBlock);
615 MachineBasicBlock::iterator Walker = UseI;
617 bool foundDef = false;
618 bool foundUse = false;
619 while (Walker != MBB->begin()) {
620 if (BlockDefs.count(Walker)) {
623 } else if (BlockUses.count(Walker)) {
630 // Must check begin() too.
631 if (!foundDef && !foundUse) {
632 if (BlockDefs.count(Walker))
634 else if (BlockUses.count(Walker))
637 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
638 Uses, NewVNs, LiveOut, Phis,
639 IsTopLevel, IsIntraBlock);
642 unsigned StartIndex = LIs->getInstructionIndex(Walker);
643 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
644 LiveIntervals::getUseIndex(StartIndex);
645 unsigned EndIndex = 0;
647 EndIndex = LIs->getInstructionIndex(UseI);
648 EndIndex = LiveIntervals::getUseIndex(EndIndex);
650 EndIndex = LIs->getMBBEndIdx(MBB);
653 RetVNI = NewVNs[Walker];
655 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
656 NewVNs, LiveOut, Phis, false, true);
658 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
660 if (foundUse && LI->isKill(RetVNI, StartIndex))
661 LI->removeKill(RetVNI, StartIndex);
663 LI->addKill(RetVNI, EndIndex);
667 // Memoize results so we don't have to recompute them.
668 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
670 if (!NewVNs.count(UseI))
671 NewVNs[UseI] = RetVNI;
672 Visited.insert(UseI);
678 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
681 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
682 MachineBasicBlock* MBB, LiveInterval* LI,
683 SmallPtrSet<MachineInstr*, 4>& Visited,
684 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
685 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
686 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
687 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
688 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
689 bool IsTopLevel, bool IsIntraBlock) {
690 // NOTE: Because this is the fallback case from other cases, we do NOT
691 // assume that we are not intrablock here.
692 if (Phis.count(MBB)) return Phis[MBB];
694 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
695 VNInfo *RetVNI = Phis[MBB] = LI->getNextValue(~0U, /*FIXME*/ 0,
696 LIs->getVNInfoAllocator());
697 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
699 // If there are no uses or defs between our starting point and the
700 // beginning of the block, then recursive perform phi construction
701 // on our predecessors.
702 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
703 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
704 PE = MBB->pred_end(); PI != PE; ++PI) {
705 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
706 Visited, Defs, Uses, NewVNs,
707 LiveOut, Phis, false, false);
709 IncomingVNs[*PI] = Incoming;
712 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill) {
713 VNInfo* OldVN = RetVNI;
714 VNInfo* NewVN = IncomingVNs.begin()->second;
715 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
716 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
718 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
719 LOE = LiveOut.end(); LOI != LOE; ++LOI)
720 if (LOI->second == OldVN)
721 LOI->second = MergedVN;
722 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
723 NVE = NewVNs.end(); NVI != NVE; ++NVI)
724 if (NVI->second == OldVN)
725 NVI->second = MergedVN;
726 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
727 PE = Phis.end(); PI != PE; ++PI)
728 if (PI->second == OldVN)
729 PI->second = MergedVN;
732 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
733 // VNInfo to represent the joined value.
734 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
735 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
736 I->second->hasPHIKill = true;
737 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
738 if (!LiveInterval::isKill(I->second, KillIndex))
739 LI->addKill(I->second, KillIndex);
743 unsigned EndIndex = 0;
745 EndIndex = LIs->getInstructionIndex(UseI);
746 EndIndex = LiveIntervals::getUseIndex(EndIndex);
748 EndIndex = LIs->getMBBEndIdx(MBB);
749 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
751 LI->addKill(RetVNI, EndIndex);
753 // Memoize results so we don't have to recompute them.
755 LiveOut[MBB] = RetVNI;
757 if (!NewVNs.count(UseI))
758 NewVNs[UseI] = RetVNI;
759 Visited.insert(UseI);
765 /// ReconstructLiveInterval - Recompute a live interval from scratch.
766 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
767 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
769 // Clear the old ranges and valnos;
772 // Cache the uses and defs of the register
773 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
776 // Keep track of the new VNs we're creating.
777 DenseMap<MachineInstr*, VNInfo*> NewVNs;
778 SmallPtrSet<VNInfo*, 2> PhiVNs;
780 // Cache defs, and create a new VNInfo for each def.
781 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
782 DE = MRI->def_end(); DI != DE; ++DI) {
783 Defs[(*DI).getParent()].insert(&*DI);
785 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
786 DefIdx = LiveIntervals::getDefIndex(DefIdx);
788 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
790 // If the def is a move, set the copy field.
791 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
792 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
793 if (DstReg == LI->reg)
796 NewVNs[&*DI] = NewVN;
799 // Cache uses as a separate pass from actually processing them.
800 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
801 UE = MRI->use_end(); UI != UE; ++UI)
802 Uses[(*UI).getParent()].insert(&*UI);
804 // Now, actually process every use and use a phi construction algorithm
805 // to walk from it to its reaching definitions, building VNInfos along
807 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
808 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
809 SmallPtrSet<MachineInstr*, 4> Visited;
810 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
811 UE = MRI->use_end(); UI != UE; ++UI) {
812 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
813 Uses, NewVNs, LiveOut, Phis, true, true);
816 // Add ranges for dead defs
817 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
818 DE = MRI->def_end(); DI != DE; ++DI) {
819 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
820 DefIdx = LiveIntervals::getDefIndex(DefIdx);
822 if (LI->liveAt(DefIdx)) continue;
824 VNInfo* DeadVN = NewVNs[&*DI];
825 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
826 LI->addKill(DeadVN, DefIdx);
830 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
831 /// be allocated to a different register. This function creates a new vreg,
832 /// copies the valno and its live ranges over to the new vreg's interval,
833 /// removes them from the old interval, and rewrites all uses and defs of
834 /// the original reg to the new vreg within those ranges.
835 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
836 SmallVector<VNInfo*, 4> Stack;
837 SmallVector<VNInfo*, 4> VNsToCopy;
840 // Walk through and copy the valno we care about, and any other valnos
841 // that are two-address redefinitions of the one we care about. These
842 // will need to be rewritten as well. We also check for safety of the
843 // renumbering here, by making sure that none of the valno involved has
845 while (!Stack.empty()) {
846 VNInfo* OldVN = Stack.back();
849 // Bail out if we ever encounter a valno that has a PHI kill. We can't
851 if (OldVN->hasPHIKill) return;
853 VNsToCopy.push_back(OldVN);
855 // Locate two-address redefinitions
856 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
857 KE = OldVN->kills.end(); KI != KE; ++KI) {
858 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
859 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
860 if (DefIdx == ~0U) continue;
861 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
863 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
864 if (NextVN == OldVN) continue;
865 Stack.push_back(NextVN);
870 // Create the new vreg
871 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
873 // Create the new live interval
874 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
876 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
877 VNsToCopy.end(); OI != OE; ++OI) {
880 // Copy the valno over
881 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
882 LIs->getVNInfoAllocator());
883 NewLI.copyValNumInfo(NewVN, OldVN);
884 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
886 // Remove the valno from the old interval
887 CurrLI->removeValNo(OldVN);
890 // Rewrite defs and uses. This is done in two stages to avoid invalidating
892 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
894 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
895 E = MRI->reg_end(); I != E; ++I) {
896 MachineOperand& MO = I.getOperand();
897 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
899 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
900 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
901 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
904 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
905 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
906 MachineInstr* Inst = I->first;
907 unsigned OpIdx = I->second;
908 MachineOperand& MO = Inst->getOperand(OpIdx);
912 // The renumbered vreg shares a stack slot with the old register.
913 if (IntervalSSMap.count(CurrLI->reg))
914 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
919 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
921 MachineBasicBlock::iterator RestorePt,
923 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
924 MachineBasicBlock& MBB = *RestorePt->getParent();
926 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
927 unsigned KillIdx = 0;
928 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
929 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
931 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
933 if (KillPt == DefMI->getParent()->end())
936 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
937 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
939 ReconstructLiveInterval(CurrLI);
940 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
941 RematIdx = LiveIntervals::getDefIndex(RematIdx);
942 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
949 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
950 const TargetRegisterClass* RC,
952 MachineInstr* Barrier,
953 MachineBasicBlock* MBB,
955 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
956 MachineBasicBlock::iterator Pt = MBB->begin();
958 // Go top down if RefsInMBB is empty.
959 if (RefsInMBB.empty())
962 MachineBasicBlock::iterator FoldPt = Barrier;
963 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
964 !RefsInMBB.count(FoldPt))
967 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
971 SmallVector<unsigned, 1> Ops;
972 Ops.push_back(OpIdx);
974 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
977 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
978 if (I != IntervalSSMap.end()) {
981 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
985 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
989 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
990 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
993 IntervalSSMap[vreg] = SS;
994 CurrSLI = &LSs->getOrCreateInterval(SS);
995 if (CurrSLI->hasAtLeastOneValue())
996 CurrSValNo = CurrSLI->getValNumInfo(0);
998 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1004 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1005 /// so it would not cross the barrier that's being processed. Shrink wrap
1006 /// (minimize) the live interval to the last uses.
1007 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1010 // Find live range where current interval cross the barrier.
1011 LiveInterval::iterator LR =
1012 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1013 VNInfo *ValNo = LR->valno;
1015 if (ValNo->def == ~1U) {
1016 // Defined by a dead def? How can this be?
1017 assert(0 && "Val# is defined by a dead def?");
1021 MachineInstr *DefMI = (ValNo->def != ~0U)
1022 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1024 // If this would create a new join point, do not split.
1025 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1028 // Find all references in the barrier mbb.
1029 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1030 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1031 E = MRI->reg_end(); I != E; ++I) {
1032 MachineInstr *RefMI = &*I;
1033 if (RefMI->getParent() == BarrierMBB)
1034 RefsInMBB.insert(RefMI);
1037 // Find a point to restore the value after the barrier.
1038 unsigned RestoreIndex = 0;
1039 MachineBasicBlock::iterator RestorePt =
1040 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1041 if (RestorePt == BarrierMBB->end())
1044 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1045 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1046 RestoreIndex, RefsInMBB))
1049 // Add a spill either before the barrier or after the definition.
1050 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1051 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1052 unsigned SpillIndex = 0;
1053 MachineInstr *SpillMI = NULL;
1055 if (ValNo->def == ~0U) {
1056 // If it's defined by a phi, we must split just before the barrier.
1057 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1058 BarrierMBB, SS, RefsInMBB))) {
1059 SpillIndex = LIs->getInstructionIndex(SpillMI);
1061 MachineBasicBlock::iterator SpillPt =
1062 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1063 if (SpillPt == BarrierMBB->begin())
1064 return false; // No gap to insert spill.
1067 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1068 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1069 SpillMI = prior(SpillPt);
1070 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1072 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1073 RestoreIndex, SpillIndex, SS)) {
1074 // If it's already split, just restore the value. There is no need to spill
1077 return false; // Def is dead. Do nothing.
1079 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1080 BarrierMBB, SS, RefsInMBB))) {
1081 SpillIndex = LIs->getInstructionIndex(SpillMI);
1083 // Check if it's possible to insert a spill after the def MI.
1084 MachineBasicBlock::iterator SpillPt;
1085 if (DefMBB == BarrierMBB) {
1086 // Add spill after the def and the last use before the barrier.
1087 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1088 RefsInMBB, SpillIndex);
1089 if (SpillPt == DefMBB->begin())
1090 return false; // No gap to insert spill.
1092 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1093 if (SpillPt == DefMBB->end())
1094 return false; // No gap to insert spill.
1096 // Add spill. The store instruction kills the register if def is before
1097 // the barrier in the barrier block.
1098 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1099 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1100 DefMBB == BarrierMBB, SS, RC);
1101 SpillMI = prior(SpillPt);
1102 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1106 // Remember def instruction index to spill index mapping.
1107 if (DefMI && SpillMI)
1108 Def2SpillMap[ValNo->def] = SpillIndex;
1111 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1112 MachineInstr *LoadMI = prior(RestorePt);
1113 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1115 // Update spill stack slot live interval.
1116 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1117 LIs->getDefIndex(RestoreIndex));
1119 ReconstructLiveInterval(CurrLI);
1120 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1121 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1122 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1128 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1129 /// barrier that's being processed.
1131 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1132 SmallPtrSet<LiveInterval*, 8>& Split) {
1133 // First find all the virtual registers whose live intervals are intercepted
1134 // by the current barrier.
1135 SmallVector<LiveInterval*, 8> Intervals;
1136 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1137 // FIXME: If it's not safe to move any instruction that defines the barrier
1138 // register class, then it means there are some special dependencies which
1139 // codegen is not modelling. Ignore these barriers for now.
1140 if (!TII->isSafeToMoveRegClassDefs(*RC))
1142 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1143 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1144 unsigned Reg = VRs[i];
1145 if (!LIs->hasInterval(Reg))
1147 LiveInterval *LI = &LIs->getInterval(Reg);
1148 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1149 // Virtual register live interval is intercepted by the barrier. We
1150 // should split and shrink wrap its interval if possible.
1151 Intervals.push_back(LI);
1155 // Process the affected live intervals.
1156 bool Change = false;
1157 while (!Intervals.empty()) {
1158 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1160 else if (NumSplits == 4)
1162 LiveInterval *LI = Intervals.back();
1163 Intervals.pop_back();
1164 bool result = SplitRegLiveInterval(LI);
1165 if (result) Split.insert(LI);
1172 unsigned PreAllocSplitting::getNumberOfNonSpills(
1173 SmallPtrSet<MachineInstr*, 4>& MIs,
1174 unsigned Reg, int FrameIndex,
1175 bool& FeedsTwoAddr) {
1176 unsigned NonSpills = 0;
1177 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1179 int StoreFrameIndex;
1180 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1181 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1184 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1185 if (DefIdx != -1 && (*UI)->isRegReDefinedByTwoAddr(DefIdx))
1186 FeedsTwoAddr = true;
1192 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1193 /// split, and see if any of the spills are unnecessary. If so, remove them.
1194 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1195 bool changed = false;
1197 // Walk over all of the live intervals that were touched by the splitter,
1198 // and see if we can do any DCE and/or folding.
1199 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1200 LE = split.end(); LI != LE; ++LI) {
1201 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1203 // First, collect all the uses of the vreg, and sort them by their
1204 // reaching definition (VNInfo).
1205 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1206 UE = MRI->use_end(); UI != UE; ++UI) {
1207 unsigned index = LIs->getInstructionIndex(&*UI);
1208 index = LiveIntervals::getUseIndex(index);
1210 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1211 VNUseCount[LR->valno].insert(&*UI);
1214 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1215 // and/or fold them away.
1216 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1217 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1219 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1222 VNInfo* CurrVN = *VI;
1224 // We don't currently try to handle definitions with PHI kills, because
1225 // it would involve processing more than one VNInfo at once.
1226 if (CurrVN->hasPHIKill) continue;
1228 // We also don't try to handle the results of PHI joins, since there's
1229 // no defining instruction to analyze.
1230 unsigned DefIdx = CurrVN->def;
1231 if (DefIdx == ~0U || DefIdx == ~1U) continue;
1233 // We're only interested in eliminating cruft introduced by the splitter,
1234 // is of the form load-use or load-use-store. First, check that the
1235 // definition is a load, and remember what stack slot we loaded it from.
1236 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1238 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1240 // If the definition has no uses at all, just DCE it.
1241 if (VNUseCount[CurrVN].size() == 0) {
1242 LIs->RemoveMachineInstrFromMaps(DefMI);
1243 (*LI)->removeValNo(CurrVN);
1244 DefMI->eraseFromParent();
1245 VNUseCount.erase(CurrVN);
1251 // Second, get the number of non-store uses of the definition, as well as
1252 // a flag indicating whether it feeds into a later two-address definition.
1253 bool FeedsTwoAddr = false;
1254 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1255 (*LI)->reg, FrameIndex,
1258 // If there's one non-store use and it doesn't feed a two-addr, then
1259 // this is a load-use-store case that we can try to fold.
1260 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1261 // Start by finding the non-store use MachineInstr.
1262 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1263 int StoreFrameIndex;
1264 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1265 while (UI != VNUseCount[CurrVN].end() &&
1266 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1268 if (UI != VNUseCount[CurrVN].end())
1269 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1271 if (UI == VNUseCount[CurrVN].end()) continue;
1273 MachineInstr* use = *UI;
1275 // Attempt to fold it away!
1276 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1277 if (OpIdx == -1) continue;
1278 SmallVector<unsigned, 1> Ops;
1279 Ops.push_back(OpIdx);
1280 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1282 MachineInstr* NewMI =
1283 TII->foldMemoryOperand(*use->getParent()->getParent(),
1284 use, Ops, FrameIndex);
1286 if (!NewMI) continue;
1288 // Update relevant analyses.
1289 LIs->RemoveMachineInstrFromMaps(DefMI);
1290 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1291 (*LI)->removeValNo(CurrVN);
1293 DefMI->eraseFromParent();
1294 MachineBasicBlock* MBB = use->getParent();
1295 NewMI = MBB->insert(MBB->erase(use), NewMI);
1296 VNUseCount[CurrVN].erase(use);
1298 // Remove deleted instructions. Note that we need to remove them from
1299 // the VNInfo->use map as well, just to be safe.
1300 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1301 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1303 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1304 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1306 if (VNI->first != CurrVN)
1307 VNI->second.erase(*II);
1308 LIs->RemoveMachineInstrFromMaps(*II);
1309 (*II)->eraseFromParent();
1312 VNUseCount.erase(CurrVN);
1314 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1315 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1316 if (VI->second.erase(use))
1317 VI->second.insert(NewMI);
1324 // If there's more than one non-store instruction, we can't profitably
1325 // fold it, so bail.
1326 if (NonSpillCount) continue;
1328 // Otherwise, this is a load-store case, so DCE them.
1329 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1330 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1332 LIs->RemoveMachineInstrFromMaps(*UI);
1333 (*UI)->eraseFromParent();
1336 VNUseCount.erase(CurrVN);
1338 LIs->RemoveMachineInstrFromMaps(DefMI);
1339 (*LI)->removeValNo(CurrVN);
1340 DefMI->eraseFromParent();
1349 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1350 MachineBasicBlock* DefMBB,
1351 MachineBasicBlock* BarrierMBB) {
1352 if (DefMBB == BarrierMBB)
1355 if (LR->valno->hasPHIKill)
1358 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1359 if (LR->end < MBBEnd)
1362 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1363 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1366 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1367 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1368 typedef std::pair<MachineBasicBlock*,
1369 MachineBasicBlock::succ_iterator> ItPair;
1370 SmallVector<ItPair, 4> Stack;
1371 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1373 while (!Stack.empty()) {
1374 ItPair P = Stack.back();
1377 MachineBasicBlock* PredMBB = P.first;
1378 MachineBasicBlock::succ_iterator S = P.second;
1380 if (S == PredMBB->succ_end())
1382 else if (Visited.count(*S)) {
1383 Stack.push_back(std::make_pair(PredMBB, ++S));
1386 Stack.push_back(std::make_pair(PredMBB, S+1));
1388 MachineBasicBlock* MBB = *S;
1389 Visited.insert(MBB);
1391 if (MBB == BarrierMBB)
1394 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1395 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1396 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1398 if (MDTN == DefMDTN)
1400 else if (MDTN == BarrierMDTN)
1402 MDTN = MDTN->getIDom();
1405 MBBEnd = LIs->getMBBEndIdx(MBB);
1406 if (LR->end > MBBEnd)
1407 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1414 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1416 TM = &MF.getTarget();
1417 TRI = TM->getRegisterInfo();
1418 TII = TM->getInstrInfo();
1419 MFI = MF.getFrameInfo();
1420 MRI = &MF.getRegInfo();
1421 LIs = &getAnalysis<LiveIntervals>();
1422 LSs = &getAnalysis<LiveStacks>();
1424 bool MadeChange = false;
1426 // Make sure blocks are numbered in order.
1427 MF.RenumberBlocks();
1429 MachineBasicBlock *Entry = MF.begin();
1430 SmallPtrSet<MachineBasicBlock*,16> Visited;
1432 SmallPtrSet<LiveInterval*, 8> Split;
1434 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1435 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1438 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1439 E = BarrierMBB->end(); I != E; ++I) {
1441 const TargetRegisterClass **BarrierRCs =
1442 Barrier->getDesc().getRegClassBarriers();
1445 BarrierIdx = LIs->getInstructionIndex(Barrier);
1446 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1450 MadeChange |= removeDeadSpills(Split);