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;
229 unsigned Index = LIs->getInstructionIndex(MII);
230 unsigned Gap = LIs->findGapBeforeInstr(Index);
236 // We can't insert the spill between the barrier (a call), and its
237 // corresponding call frame setup.
238 } else if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode() &&
239 MII == MachineBasicBlock::iterator(MI))
241 } while (MII != EndPt);
243 MachineBasicBlock::iterator MII = MI;
244 MachineBasicBlock::iterator EndPt = DefMI
245 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
247 // We can't insert the spill between the barrier (a call), and its
248 // corresponding call frame setup.
249 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) --MII;
250 while (MII != EndPt && !RefsInMBB.count(MII)) {
251 unsigned Index = LIs->getInstructionIndex(MII);
252 if (LIs->hasGapBeforeInstr(Index)) {
254 SpillIndex = LIs->findGapBeforeInstr(Index, true);
263 /// findRestorePoint - Find a gap in the instruction index map that's suitable
264 /// for restoring the current live interval value. The index must be before any
265 /// uses of the live interval register in the mbb. Return end() if none is
267 MachineBasicBlock::iterator
268 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
270 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
271 unsigned &RestoreIndex) {
272 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
273 // begin index accordingly.
274 MachineBasicBlock::iterator Pt = MBB->end();
275 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
277 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
278 // the last index in the live range.
279 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
280 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
281 MachineBasicBlock::iterator EndPt = MI;
284 unsigned Index = LIs->getInstructionIndex(MII);
285 unsigned Gap = LIs->findGapBeforeInstr(Index);
291 // We can't insert a restore between the barrier (a call) and its
292 // corresponding call frame teardown.
293 } else if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode() &&
294 prior(MII) == MachineBasicBlock::iterator(MI))
297 } while (MII != EndPt);
299 MachineBasicBlock::iterator MII = MI;
301 // We can't insert a restore between the barrier (a call) and its
302 // corresponding call frame teardown.
303 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode())
306 // FIXME: Limit the number of instructions to examine to reduce
308 while (MII != MBB->getFirstTerminator()) {
309 unsigned Index = LIs->getInstructionIndex(MII);
312 unsigned Gap = LIs->findGapBeforeInstr(Index);
317 if (RefsInMBB.count(MII))
326 /// CreateSpillStackSlot - Create a stack slot for the live interval being
327 /// split. If the live interval was previously split, just reuse the same
329 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
330 const TargetRegisterClass *RC) {
332 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
333 if (I != IntervalSSMap.end()) {
336 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
337 IntervalSSMap[Reg] = SS;
340 // Create live interval for stack slot.
341 CurrSLI = &LSs->getOrCreateInterval(SS);
342 if (CurrSLI->hasAtLeastOneValue())
343 CurrSValNo = CurrSLI->getValNumInfo(0);
345 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
349 /// IsAvailableInStack - Return true if register is available in a split stack
350 /// slot at the specified index.
352 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
353 unsigned Reg, unsigned DefIndex,
354 unsigned RestoreIndex, unsigned &SpillIndex,
359 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
360 if (I == IntervalSSMap.end())
362 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
363 if (II == Def2SpillMap.end())
366 // If last spill of def is in the same mbb as barrier mbb (where restore will
367 // be), make sure it's not below the intended restore index.
368 // FIXME: Undo the previous spill?
369 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
370 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
374 SpillIndex = II->second;
378 /// UpdateSpillSlotInterval - Given the specified val# of the register live
379 /// interval being split, and the spill and restore indicies, update the live
380 /// interval of the spill stack slot.
382 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
383 unsigned RestoreIndex) {
384 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
385 "Expect restore in the barrier mbb");
387 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
388 if (MBB == BarrierMBB) {
389 // Intra-block spill + restore. We are done.
390 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
391 CurrSLI->addRange(SLR);
395 SmallPtrSet<MachineBasicBlock*, 4> Processed;
396 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
397 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
398 CurrSLI->addRange(SLR);
399 Processed.insert(MBB);
401 // Start from the spill mbb, figure out the extend of the spill slot's
403 SmallVector<MachineBasicBlock*, 4> WorkList;
404 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
405 if (LR->end > EndIdx)
406 // If live range extend beyond end of mbb, add successors to work list.
407 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
408 SE = MBB->succ_end(); SI != SE; ++SI)
409 WorkList.push_back(*SI);
411 while (!WorkList.empty()) {
412 MachineBasicBlock *MBB = WorkList.back();
414 if (Processed.count(MBB))
416 unsigned Idx = LIs->getMBBStartIdx(MBB);
417 LR = CurrLI->getLiveRangeContaining(Idx);
418 if (LR && LR->valno == ValNo) {
419 EndIdx = LIs->getMBBEndIdx(MBB);
420 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
421 // Spill slot live interval stops at the restore.
422 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
423 CurrSLI->addRange(SLR);
424 } else if (LR->end > EndIdx) {
425 // Live range extends beyond end of mbb, process successors.
426 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
427 CurrSLI->addRange(SLR);
428 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
429 SE = MBB->succ_end(); SI != SE; ++SI)
430 WorkList.push_back(*SI);
432 LiveRange SLR(Idx, LR->end, CurrSValNo);
433 CurrSLI->addRange(SLR);
435 Processed.insert(MBB);
440 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
441 /// construction algorithm to compute the ranges and valnos for an interval.
443 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
444 MachineBasicBlock* MBB, LiveInterval* LI,
445 SmallPtrSet<MachineInstr*, 4>& Visited,
446 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
447 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
448 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
449 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
450 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
451 bool IsTopLevel, bool IsIntraBlock) {
452 // Return memoized result if it's available.
453 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
455 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
457 else if (!IsIntraBlock && LiveOut.count(MBB))
460 // Check if our block contains any uses or defs.
461 bool ContainsDefs = Defs.count(MBB);
462 bool ContainsUses = Uses.count(MBB);
466 // Enumerate the cases of use/def contaning blocks.
467 if (!ContainsDefs && !ContainsUses) {
468 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
469 NewVNs, LiveOut, Phis,
470 IsTopLevel, IsIntraBlock);
471 } else if (ContainsDefs && !ContainsUses) {
472 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
474 // Search for the def in this block. If we don't find it before the
475 // instruction we care about, go to the fallback case. Note that that
476 // should never happen: this cannot be intrablock, so use should
477 // always be an end() iterator.
478 assert(UseI == MBB->end() && "No use marked in intrablock");
480 MachineBasicBlock::iterator Walker = UseI;
482 while (Walker != MBB->begin()) {
483 if (BlockDefs.count(Walker))
488 // Once we've found it, extend its VNInfo to our instruction.
489 unsigned DefIndex = LIs->getInstructionIndex(Walker);
490 DefIndex = LiveIntervals::getDefIndex(DefIndex);
491 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
493 RetVNI = NewVNs[Walker];
494 LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
495 } else if (!ContainsDefs && ContainsUses) {
496 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
498 // Search for the use in this block that precedes the instruction we care
499 // about, going to the fallback case if we don't find it.
500 if (UseI == MBB->begin())
501 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
502 Uses, NewVNs, LiveOut, Phis,
503 IsTopLevel, IsIntraBlock);
505 MachineBasicBlock::iterator Walker = UseI;
508 while (Walker != MBB->begin()) {
509 if (BlockUses.count(Walker)) {
516 // Must check begin() too.
518 if (BlockUses.count(Walker))
521 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
522 Uses, NewVNs, LiveOut, Phis,
523 IsTopLevel, IsIntraBlock);
526 unsigned UseIndex = LIs->getInstructionIndex(Walker);
527 UseIndex = LiveIntervals::getUseIndex(UseIndex);
528 unsigned EndIndex = 0;
530 EndIndex = LIs->getInstructionIndex(UseI);
531 EndIndex = LiveIntervals::getUseIndex(EndIndex);
533 EndIndex = LIs->getMBBEndIdx(MBB);
535 // Now, recursively phi construct the VNInfo for the use we found,
536 // and then extend it to include the instruction we care about
537 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
538 NewVNs, LiveOut, Phis, false, true);
540 LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
542 // FIXME: Need to set kills properly for inter-block stuff.
543 if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
545 LI->addKill(RetVNI, EndIndex);
546 } else if (ContainsDefs && ContainsUses) {
547 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
548 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
550 // This case is basically a merging of the two preceding case, with the
551 // special note that checking for defs must take precedence over checking
552 // for uses, because of two-address instructions.
554 if (UseI == MBB->begin())
555 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
556 NewVNs, LiveOut, Phis,
557 IsTopLevel, IsIntraBlock);
559 MachineBasicBlock::iterator Walker = UseI;
561 bool foundDef = false;
562 bool foundUse = false;
563 while (Walker != MBB->begin()) {
564 if (BlockDefs.count(Walker)) {
567 } else if (BlockUses.count(Walker)) {
574 // Must check begin() too.
575 if (!foundDef && !foundUse) {
576 if (BlockDefs.count(Walker))
578 else if (BlockUses.count(Walker))
581 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
582 Uses, NewVNs, LiveOut, Phis,
583 IsTopLevel, IsIntraBlock);
586 unsigned StartIndex = LIs->getInstructionIndex(Walker);
587 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
588 LiveIntervals::getUseIndex(StartIndex);
589 unsigned EndIndex = 0;
591 EndIndex = LIs->getInstructionIndex(UseI);
592 EndIndex = LiveIntervals::getUseIndex(EndIndex);
594 EndIndex = LIs->getMBBEndIdx(MBB);
597 RetVNI = NewVNs[Walker];
599 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
600 NewVNs, LiveOut, Phis, false, true);
602 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
604 if (foundUse && LI->isKill(RetVNI, StartIndex))
605 LI->removeKill(RetVNI, StartIndex);
607 LI->addKill(RetVNI, EndIndex);
611 // Memoize results so we don't have to recompute them.
612 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
614 if (!NewVNs.count(UseI))
615 NewVNs[UseI] = RetVNI;
616 Visited.insert(UseI);
622 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
625 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
626 MachineBasicBlock* MBB, LiveInterval* LI,
627 SmallPtrSet<MachineInstr*, 4>& Visited,
628 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
629 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
630 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
631 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
632 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
633 bool IsTopLevel, bool IsIntraBlock) {
634 // NOTE: Because this is the fallback case from other cases, we do NOT
635 // assume that we are not intrablock here.
636 if (Phis.count(MBB)) return Phis[MBB];
638 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
639 VNInfo *RetVNI = Phis[MBB] = LI->getNextValue(~0U, /*FIXME*/ 0,
640 LIs->getVNInfoAllocator());
641 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
643 // If there are no uses or defs between our starting point and the
644 // beginning of the block, then recursive perform phi construction
645 // on our predecessors.
646 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
647 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
648 PE = MBB->pred_end(); PI != PE; ++PI) {
649 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
650 Visited, Defs, Uses, NewVNs,
651 LiveOut, Phis, false, false);
653 IncomingVNs[*PI] = Incoming;
656 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill) {
657 VNInfo* OldVN = RetVNI;
658 VNInfo* NewVN = IncomingVNs.begin()->second;
659 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
660 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
662 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
663 LOE = LiveOut.end(); LOI != LOE; ++LOI)
664 if (LOI->second == OldVN)
665 LOI->second = MergedVN;
666 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
667 NVE = NewVNs.end(); NVI != NVE; ++NVI)
668 if (NVI->second == OldVN)
669 NVI->second = MergedVN;
670 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
671 PE = Phis.end(); PI != PE; ++PI)
672 if (PI->second == OldVN)
673 PI->second = MergedVN;
676 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
677 // VNInfo to represent the joined value.
678 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
679 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
680 I->second->hasPHIKill = true;
681 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
682 if (!LiveInterval::isKill(I->second, KillIndex))
683 LI->addKill(I->second, KillIndex);
687 unsigned EndIndex = 0;
689 EndIndex = LIs->getInstructionIndex(UseI);
690 EndIndex = LiveIntervals::getUseIndex(EndIndex);
692 EndIndex = LIs->getMBBEndIdx(MBB);
693 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
695 LI->addKill(RetVNI, EndIndex);
697 // Memoize results so we don't have to recompute them.
699 LiveOut[MBB] = RetVNI;
701 if (!NewVNs.count(UseI))
702 NewVNs[UseI] = RetVNI;
703 Visited.insert(UseI);
709 /// ReconstructLiveInterval - Recompute a live interval from scratch.
710 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
711 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
713 // Clear the old ranges and valnos;
716 // Cache the uses and defs of the register
717 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
720 // Keep track of the new VNs we're creating.
721 DenseMap<MachineInstr*, VNInfo*> NewVNs;
722 SmallPtrSet<VNInfo*, 2> PhiVNs;
724 // Cache defs, and create a new VNInfo for each def.
725 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
726 DE = MRI->def_end(); DI != DE; ++DI) {
727 Defs[(*DI).getParent()].insert(&*DI);
729 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
730 DefIdx = LiveIntervals::getDefIndex(DefIdx);
732 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
734 // If the def is a move, set the copy field.
735 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
736 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
737 if (DstReg == LI->reg)
740 NewVNs[&*DI] = NewVN;
743 // Cache uses as a separate pass from actually processing them.
744 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
745 UE = MRI->use_end(); UI != UE; ++UI)
746 Uses[(*UI).getParent()].insert(&*UI);
748 // Now, actually process every use and use a phi construction algorithm
749 // to walk from it to its reaching definitions, building VNInfos along
751 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
752 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
753 SmallPtrSet<MachineInstr*, 4> Visited;
754 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
755 UE = MRI->use_end(); UI != UE; ++UI) {
756 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
757 Uses, NewVNs, LiveOut, Phis, true, true);
760 // Add ranges for dead defs
761 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
762 DE = MRI->def_end(); DI != DE; ++DI) {
763 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
764 DefIdx = LiveIntervals::getDefIndex(DefIdx);
766 if (LI->liveAt(DefIdx)) continue;
768 VNInfo* DeadVN = NewVNs[&*DI];
769 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
770 LI->addKill(DeadVN, DefIdx);
774 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
775 /// be allocated to a different register. This function creates a new vreg,
776 /// copies the valno and its live ranges over to the new vreg's interval,
777 /// removes them from the old interval, and rewrites all uses and defs of
778 /// the original reg to the new vreg within those ranges.
779 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
780 SmallVector<VNInfo*, 4> Stack;
781 SmallVector<VNInfo*, 4> VNsToCopy;
784 // Walk through and copy the valno we care about, and any other valnos
785 // that are two-address redefinitions of the one we care about. These
786 // will need to be rewritten as well. We also check for safety of the
787 // renumbering here, by making sure that none of the valno involved has
789 while (!Stack.empty()) {
790 VNInfo* OldVN = Stack.back();
793 // Bail out if we ever encounter a valno that has a PHI kill. We can't
795 if (OldVN->hasPHIKill) return;
797 VNsToCopy.push_back(OldVN);
799 // Locate two-address redefinitions
800 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
801 KE = OldVN->kills.end(); KI != KE; ++KI) {
802 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
803 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
804 if (DefIdx == ~0U) continue;
805 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
807 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
808 if (NextVN == OldVN) continue;
809 Stack.push_back(NextVN);
814 // Create the new vreg
815 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
817 // Create the new live interval
818 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
820 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
821 VNsToCopy.end(); OI != OE; ++OI) {
824 // Copy the valno over
825 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
826 LIs->getVNInfoAllocator());
827 NewLI.copyValNumInfo(NewVN, OldVN);
828 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
830 // Remove the valno from the old interval
831 CurrLI->removeValNo(OldVN);
834 // Rewrite defs and uses. This is done in two stages to avoid invalidating
836 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
838 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
839 E = MRI->reg_end(); I != E; ++I) {
840 MachineOperand& MO = I.getOperand();
841 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
843 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
844 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
845 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
848 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
849 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
850 MachineInstr* Inst = I->first;
851 unsigned OpIdx = I->second;
852 MachineOperand& MO = Inst->getOperand(OpIdx);
856 // The renumbered vreg shares a stack slot with the old register.
857 if (IntervalSSMap.count(CurrLI->reg))
858 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
863 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
865 MachineBasicBlock::iterator RestorePt,
867 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
868 MachineBasicBlock& MBB = *RestorePt->getParent();
870 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
871 unsigned KillIdx = 0;
872 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
873 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
875 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
877 if (KillPt == DefMI->getParent()->end())
880 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
881 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
883 ReconstructLiveInterval(CurrLI);
884 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
885 RematIdx = LiveIntervals::getDefIndex(RematIdx);
886 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
893 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
894 const TargetRegisterClass* RC,
896 MachineInstr* Barrier,
897 MachineBasicBlock* MBB,
899 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
900 MachineBasicBlock::iterator Pt = MBB->begin();
902 // Go top down if RefsInMBB is empty.
903 if (RefsInMBB.empty())
906 MachineBasicBlock::iterator FoldPt = Barrier;
907 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
908 !RefsInMBB.count(FoldPt))
911 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
915 SmallVector<unsigned, 1> Ops;
916 Ops.push_back(OpIdx);
918 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
921 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
922 if (I != IntervalSSMap.end()) {
925 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
929 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
933 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
934 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
937 IntervalSSMap[vreg] = SS;
938 CurrSLI = &LSs->getOrCreateInterval(SS);
939 if (CurrSLI->hasAtLeastOneValue())
940 CurrSValNo = CurrSLI->getValNumInfo(0);
942 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
948 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
949 /// so it would not cross the barrier that's being processed. Shrink wrap
950 /// (minimize) the live interval to the last uses.
951 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
954 // Find live range where current interval cross the barrier.
955 LiveInterval::iterator LR =
956 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
957 VNInfo *ValNo = LR->valno;
959 if (ValNo->def == ~1U) {
960 // Defined by a dead def? How can this be?
961 assert(0 && "Val# is defined by a dead def?");
965 MachineInstr *DefMI = (ValNo->def != ~0U)
966 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
968 // If this would create a new join point, do not split.
969 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
972 // Find all references in the barrier mbb.
973 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
974 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
975 E = MRI->reg_end(); I != E; ++I) {
976 MachineInstr *RefMI = &*I;
977 if (RefMI->getParent() == BarrierMBB)
978 RefsInMBB.insert(RefMI);
981 // Find a point to restore the value after the barrier.
982 unsigned RestoreIndex = 0;
983 MachineBasicBlock::iterator RestorePt =
984 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
985 if (RestorePt == BarrierMBB->end())
988 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
989 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
990 RestoreIndex, RefsInMBB))
993 // Add a spill either before the barrier or after the definition.
994 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
995 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
996 unsigned SpillIndex = 0;
997 MachineInstr *SpillMI = NULL;
999 if (ValNo->def == ~0U) {
1000 // If it's defined by a phi, we must split just before the barrier.
1001 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1002 BarrierMBB, SS, RefsInMBB))) {
1003 SpillIndex = LIs->getInstructionIndex(SpillMI);
1005 MachineBasicBlock::iterator SpillPt =
1006 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1007 if (SpillPt == BarrierMBB->begin())
1008 return false; // No gap to insert spill.
1011 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1012 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1013 SpillMI = prior(SpillPt);
1014 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1016 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1017 RestoreIndex, SpillIndex, SS)) {
1018 // If it's already split, just restore the value. There is no need to spill
1021 return false; // Def is dead. Do nothing.
1023 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1024 BarrierMBB, SS, RefsInMBB))) {
1025 SpillIndex = LIs->getInstructionIndex(SpillMI);
1027 // Check if it's possible to insert a spill after the def MI.
1028 MachineBasicBlock::iterator SpillPt;
1029 if (DefMBB == BarrierMBB) {
1030 // Add spill after the def and the last use before the barrier.
1031 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1032 RefsInMBB, SpillIndex);
1033 if (SpillPt == DefMBB->begin())
1034 return false; // No gap to insert spill.
1036 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1037 if (SpillPt == DefMBB->end())
1038 return false; // No gap to insert spill.
1040 // Add spill. The store instruction kills the register if def is before
1041 // the barrier in the barrier block.
1042 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1043 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1044 DefMBB == BarrierMBB, SS, RC);
1045 SpillMI = prior(SpillPt);
1046 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1050 // Remember def instruction index to spill index mapping.
1051 if (DefMI && SpillMI)
1052 Def2SpillMap[ValNo->def] = SpillIndex;
1055 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1056 MachineInstr *LoadMI = prior(RestorePt);
1057 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1059 // Update spill stack slot live interval.
1060 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1061 LIs->getDefIndex(RestoreIndex));
1063 ReconstructLiveInterval(CurrLI);
1064 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1065 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1066 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1072 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1073 /// barrier that's being processed.
1075 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1076 SmallPtrSet<LiveInterval*, 8>& Split) {
1077 // First find all the virtual registers whose live intervals are intercepted
1078 // by the current barrier.
1079 SmallVector<LiveInterval*, 8> Intervals;
1080 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1081 if (TII->IgnoreRegisterClassBarriers(*RC))
1083 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1084 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1085 unsigned Reg = VRs[i];
1086 if (!LIs->hasInterval(Reg))
1088 LiveInterval *LI = &LIs->getInterval(Reg);
1089 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1090 // Virtual register live interval is intercepted by the barrier. We
1091 // should split and shrink wrap its interval if possible.
1092 Intervals.push_back(LI);
1096 // Process the affected live intervals.
1097 bool Change = false;
1098 while (!Intervals.empty()) {
1099 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1101 else if (NumSplits == 4)
1103 LiveInterval *LI = Intervals.back();
1104 Intervals.pop_back();
1105 bool result = SplitRegLiveInterval(LI);
1106 if (result) Split.insert(LI);
1113 unsigned PreAllocSplitting::getNumberOfNonSpills(
1114 SmallPtrSet<MachineInstr*, 4>& MIs,
1115 unsigned Reg, int FrameIndex,
1116 bool& FeedsTwoAddr) {
1117 unsigned NonSpills = 0;
1118 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1120 int StoreFrameIndex;
1121 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1122 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1125 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1126 if (DefIdx != -1 && (*UI)->isRegReDefinedByTwoAddr(DefIdx))
1127 FeedsTwoAddr = true;
1133 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1134 /// split, and see if any of the spills are unnecessary. If so, remove them.
1135 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1136 bool changed = false;
1138 // Walk over all of the live intervals that were touched by the splitter,
1139 // and see if we can do any DCE and/or folding.
1140 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1141 LE = split.end(); LI != LE; ++LI) {
1142 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1144 // First, collect all the uses of the vreg, and sort them by their
1145 // reaching definition (VNInfo).
1146 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1147 UE = MRI->use_end(); UI != UE; ++UI) {
1148 unsigned index = LIs->getInstructionIndex(&*UI);
1149 index = LiveIntervals::getUseIndex(index);
1151 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1152 VNUseCount[LR->valno].insert(&*UI);
1155 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1156 // and/or fold them away.
1157 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1158 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1160 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1163 VNInfo* CurrVN = *VI;
1165 // We don't currently try to handle definitions with PHI kills, because
1166 // it would involve processing more than one VNInfo at once.
1167 if (CurrVN->hasPHIKill) continue;
1169 // We also don't try to handle the results of PHI joins, since there's
1170 // no defining instruction to analyze.
1171 unsigned DefIdx = CurrVN->def;
1172 if (DefIdx == ~0U || DefIdx == ~1U) continue;
1174 // We're only interested in eliminating cruft introduced by the splitter,
1175 // is of the form load-use or load-use-store. First, check that the
1176 // definition is a load, and remember what stack slot we loaded it from.
1177 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1179 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1181 // If the definition has no uses at all, just DCE it.
1182 if (VNUseCount[CurrVN].size() == 0) {
1183 LIs->RemoveMachineInstrFromMaps(DefMI);
1184 (*LI)->removeValNo(CurrVN);
1185 DefMI->eraseFromParent();
1186 VNUseCount.erase(CurrVN);
1192 // Second, get the number of non-store uses of the definition, as well as
1193 // a flag indicating whether it feeds into a later two-address definition.
1194 bool FeedsTwoAddr = false;
1195 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1196 (*LI)->reg, FrameIndex,
1199 // If there's one non-store use and it doesn't feed a two-addr, then
1200 // this is a load-use-store case that we can try to fold.
1201 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1202 // Start by finding the non-store use MachineInstr.
1203 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1204 int StoreFrameIndex;
1205 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1206 while (UI != VNUseCount[CurrVN].end() &&
1207 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1209 if (UI != VNUseCount[CurrVN].end())
1210 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1212 if (UI == VNUseCount[CurrVN].end()) continue;
1214 MachineInstr* use = *UI;
1216 // Attempt to fold it away!
1217 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1218 if (OpIdx == -1) continue;
1219 SmallVector<unsigned, 1> Ops;
1220 Ops.push_back(OpIdx);
1221 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1223 MachineInstr* NewMI =
1224 TII->foldMemoryOperand(*use->getParent()->getParent(),
1225 use, Ops, FrameIndex);
1227 if (!NewMI) continue;
1229 // Update relevant analyses.
1230 LIs->RemoveMachineInstrFromMaps(DefMI);
1231 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1232 (*LI)->removeValNo(CurrVN);
1234 DefMI->eraseFromParent();
1235 MachineBasicBlock* MBB = use->getParent();
1236 NewMI = MBB->insert(MBB->erase(use), NewMI);
1237 VNUseCount[CurrVN].erase(use);
1239 // Remove deleted instructions. Note that we need to remove them from
1240 // the VNInfo->use map as well, just to be safe.
1241 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1242 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1244 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1245 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1247 if (VNI->first != CurrVN)
1248 VNI->second.erase(*II);
1249 LIs->RemoveMachineInstrFromMaps(*II);
1250 (*II)->eraseFromParent();
1253 VNUseCount.erase(CurrVN);
1255 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1256 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1257 if (VI->second.erase(use))
1258 VI->second.insert(NewMI);
1265 // If there's more than one non-store instruction, we can't profitably
1266 // fold it, so bail.
1267 if (NonSpillCount) continue;
1269 // Otherwise, this is a load-store case, so DCE them.
1270 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1271 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1273 LIs->RemoveMachineInstrFromMaps(*UI);
1274 (*UI)->eraseFromParent();
1277 VNUseCount.erase(CurrVN);
1279 LIs->RemoveMachineInstrFromMaps(DefMI);
1280 (*LI)->removeValNo(CurrVN);
1281 DefMI->eraseFromParent();
1290 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1291 MachineBasicBlock* DefMBB,
1292 MachineBasicBlock* BarrierMBB) {
1293 if (DefMBB == BarrierMBB)
1296 if (LR->valno->hasPHIKill)
1299 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1300 if (LR->end < MBBEnd)
1303 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1304 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1307 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1308 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1309 typedef std::pair<MachineBasicBlock*,
1310 MachineBasicBlock::succ_iterator> ItPair;
1311 SmallVector<ItPair, 4> Stack;
1312 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1314 while (!Stack.empty()) {
1315 ItPair P = Stack.back();
1318 MachineBasicBlock* PredMBB = P.first;
1319 MachineBasicBlock::succ_iterator S = P.second;
1321 if (S == PredMBB->succ_end())
1323 else if (Visited.count(*S)) {
1324 Stack.push_back(std::make_pair(PredMBB, ++S));
1327 Stack.push_back(std::make_pair(PredMBB, S+1));
1329 MachineBasicBlock* MBB = *S;
1330 Visited.insert(MBB);
1332 if (MBB == BarrierMBB)
1335 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1336 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1337 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1339 if (MDTN == DefMDTN)
1341 else if (MDTN == BarrierMDTN)
1343 MDTN = MDTN->getIDom();
1346 MBBEnd = LIs->getMBBEndIdx(MBB);
1347 if (LR->end > MBBEnd)
1348 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1355 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1357 TM = &MF.getTarget();
1358 TRI = TM->getRegisterInfo();
1359 TII = TM->getInstrInfo();
1360 MFI = MF.getFrameInfo();
1361 MRI = &MF.getRegInfo();
1362 LIs = &getAnalysis<LiveIntervals>();
1363 LSs = &getAnalysis<LiveStacks>();
1365 bool MadeChange = false;
1367 // Make sure blocks are numbered in order.
1368 MF.RenumberBlocks();
1370 MachineBasicBlock *Entry = MF.begin();
1371 SmallPtrSet<MachineBasicBlock*,16> Visited;
1373 SmallPtrSet<LiveInterval*, 8> Split;
1375 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1376 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1379 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1380 E = BarrierMBB->end(); I != E; ++I) {
1382 const TargetRegisterClass **BarrierRCs =
1383 Barrier->getDesc().getRegClassBarriers();
1386 BarrierIdx = LIs->getInstructionIndex(Barrier);
1387 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1391 MadeChange |= removeDeadSpills(Split);