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 "VirtRegMap.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveStackAnalysis.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/Statistic.h"
41 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
42 static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1),
44 static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1),
47 STATISTIC(NumSplits, "Number of intervals split");
48 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
49 STATISTIC(NumFolds, "Number of intervals split with spill folding");
50 STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
51 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
52 STATISTIC(NumDeadSpills, "Number of dead spills removed");
55 class PreAllocSplitting : public MachineFunctionPass {
56 MachineFunction *CurrMF;
57 const TargetMachine *TM;
58 const TargetInstrInfo *TII;
59 const TargetRegisterInfo* TRI;
60 MachineFrameInfo *MFI;
61 MachineRegisterInfo *MRI;
67 // Barrier - Current barrier being processed.
68 MachineInstr *Barrier;
70 // BarrierMBB - Basic block where the barrier resides in.
71 MachineBasicBlock *BarrierMBB;
73 // Barrier - Current barrier index.
76 // CurrLI - Current live interval being split.
79 // CurrSLI - Current stack slot live interval.
80 LiveInterval *CurrSLI;
82 // CurrSValNo - Current val# for the stack slot live interval.
85 // IntervalSSMap - A map from live interval to spill slots.
86 DenseMap<unsigned, int> IntervalSSMap;
88 // Def2SpillMap - A map from a def instruction index to spill index.
89 DenseMap<SlotIndex, SlotIndex> Def2SpillMap;
94 : MachineFunctionPass(&ID) {}
96 virtual bool runOnMachineFunction(MachineFunction &MF);
98 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<SlotIndexes>();
101 AU.addPreserved<SlotIndexes>();
102 AU.addRequired<LiveIntervals>();
103 AU.addPreserved<LiveIntervals>();
104 AU.addRequired<LiveStacks>();
105 AU.addPreserved<LiveStacks>();
106 AU.addPreserved<RegisterCoalescer>();
108 AU.addPreservedID(StrongPHIEliminationID);
110 AU.addPreservedID(PHIEliminationID);
111 AU.addRequired<MachineDominatorTree>();
112 AU.addRequired<MachineLoopInfo>();
113 AU.addRequired<VirtRegMap>();
114 AU.addPreserved<MachineDominatorTree>();
115 AU.addPreserved<MachineLoopInfo>();
116 AU.addPreserved<VirtRegMap>();
117 MachineFunctionPass::getAnalysisUsage(AU);
120 virtual void releaseMemory() {
121 IntervalSSMap.clear();
122 Def2SpillMap.clear();
125 virtual const char *getPassName() const {
126 return "Pre-Register Allocaton Live Interval Splitting";
129 /// print - Implement the dump method.
130 virtual void print(raw_ostream &O, const Module* M = 0) const {
137 MachineBasicBlock::iterator
138 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
139 SmallPtrSet<MachineInstr*, 4>&);
141 MachineBasicBlock::iterator
142 findRestorePoint(MachineBasicBlock*, MachineInstr*, SlotIndex,
143 SmallPtrSet<MachineInstr*, 4>&);
145 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
147 bool IsAvailableInStack(MachineBasicBlock*, unsigned,
148 SlotIndex, SlotIndex,
149 SlotIndex&, int&) const;
151 void UpdateSpillSlotInterval(VNInfo*, SlotIndex, SlotIndex);
153 bool SplitRegLiveInterval(LiveInterval*);
155 bool SplitRegLiveIntervals(const TargetRegisterClass **,
156 SmallPtrSet<LiveInterval*, 8>&);
158 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
159 MachineBasicBlock* BarrierMBB);
160 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
162 MachineBasicBlock::iterator RestorePt,
163 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
164 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
166 MachineInstr* Barrier,
167 MachineBasicBlock* MBB,
169 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
170 MachineInstr* FoldRestore(unsigned vreg,
171 const TargetRegisterClass* RC,
172 MachineInstr* Barrier,
173 MachineBasicBlock* MBB,
175 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
176 void RenumberValno(VNInfo* VN);
177 void ReconstructLiveInterval(LiveInterval* LI);
178 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
179 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
180 unsigned Reg, int FrameIndex, bool& TwoAddr);
181 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
182 MachineBasicBlock* MBB, LiveInterval* LI,
183 SmallPtrSet<MachineInstr*, 4>& Visited,
184 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
185 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
186 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
187 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
188 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
189 bool IsTopLevel, bool IsIntraBlock);
190 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
191 MachineBasicBlock* MBB, LiveInterval* LI,
192 SmallPtrSet<MachineInstr*, 4>& Visited,
193 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
194 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
195 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
196 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
197 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
198 bool IsTopLevel, bool IsIntraBlock);
200 } // end anonymous namespace
202 char PreAllocSplitting::ID = 0;
204 static RegisterPass<PreAllocSplitting>
205 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
207 const PassInfo *const llvm::PreAllocSplittingID = &X;
209 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
210 /// for spilling the current live interval. The index must be before any
211 /// defs and uses of the live interval register in the mbb. Return begin() if
213 MachineBasicBlock::iterator
214 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
216 SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
217 MachineBasicBlock::iterator Pt = MBB->begin();
219 MachineBasicBlock::iterator MII = MI;
220 MachineBasicBlock::iterator EndPt = DefMI
221 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
223 while (MII != EndPt && !RefsInMBB.count(MII) &&
224 MII->getOpcode() != TRI->getCallFrameSetupOpcode())
226 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
228 while (MII != EndPt && !RefsInMBB.count(MII)) {
229 // We can't insert the spill between the barrier (a call), and its
230 // corresponding call frame setup.
231 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
232 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
243 if (RefsInMBB.count(MII))
253 /// findRestorePoint - Find a gap in the instruction index map that's suitable
254 /// for restoring the current live interval value. The index must be before any
255 /// uses of the live interval register in the mbb. Return end() if none is
257 MachineBasicBlock::iterator
258 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
260 SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
261 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
262 // begin index accordingly.
263 MachineBasicBlock::iterator Pt = MBB->end();
264 MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
266 // We start at the call, so walk forward until we find the call frame teardown
267 // since we can't insert restores before that. Bail if we encounter a use
269 MachineBasicBlock::iterator MII = MI;
270 if (MII == EndPt) return Pt;
272 while (MII != EndPt && !RefsInMBB.count(MII) &&
273 MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
275 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
278 // FIXME: Limit the number of instructions to examine to reduce
280 while (MII != EndPt) {
281 SlotIndex Index = LIs->getInstructionIndex(MII);
285 // We can't insert a restore between the barrier (a call) and its
286 // corresponding call frame teardown.
287 if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
289 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
291 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
296 if (RefsInMBB.count(MII))
305 /// CreateSpillStackSlot - Create a stack slot for the live interval being
306 /// split. If the live interval was previously split, just reuse the same
308 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
309 const TargetRegisterClass *RC) {
311 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
312 if (I != IntervalSSMap.end()) {
315 SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
316 IntervalSSMap[Reg] = SS;
319 // Create live interval for stack slot.
320 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
321 if (CurrSLI->hasAtLeastOneValue())
322 CurrSValNo = CurrSLI->getValNumInfo(0);
324 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
325 LSs->getVNInfoAllocator());
329 /// IsAvailableInStack - Return true if register is available in a split stack
330 /// slot at the specified index.
332 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
333 unsigned Reg, SlotIndex DefIndex,
334 SlotIndex RestoreIndex,
335 SlotIndex &SpillIndex,
340 DenseMap<unsigned, int>::const_iterator I = IntervalSSMap.find(Reg);
341 if (I == IntervalSSMap.end())
343 DenseMap<SlotIndex, SlotIndex>::const_iterator
344 II = Def2SpillMap.find(DefIndex);
345 if (II == Def2SpillMap.end())
348 // If last spill of def is in the same mbb as barrier mbb (where restore will
349 // be), make sure it's not below the intended restore index.
350 // FIXME: Undo the previous spill?
351 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
352 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
356 SpillIndex = II->second;
360 /// UpdateSpillSlotInterval - Given the specified val# of the register live
361 /// interval being split, and the spill and restore indicies, update the live
362 /// interval of the spill stack slot.
364 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, SlotIndex SpillIndex,
365 SlotIndex RestoreIndex) {
366 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
367 "Expect restore in the barrier mbb");
369 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
370 if (MBB == BarrierMBB) {
371 // Intra-block spill + restore. We are done.
372 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
373 CurrSLI->addRange(SLR);
377 SmallPtrSet<MachineBasicBlock*, 4> Processed;
378 SlotIndex EndIdx = LIs->getMBBEndIdx(MBB);
379 LiveRange SLR(SpillIndex, EndIdx.getNextSlot(), CurrSValNo);
380 CurrSLI->addRange(SLR);
381 Processed.insert(MBB);
383 // Start from the spill mbb, figure out the extend of the spill slot's
385 SmallVector<MachineBasicBlock*, 4> WorkList;
386 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
387 if (LR->end > EndIdx)
388 // If live range extend beyond end of mbb, add successors to work list.
389 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
390 SE = MBB->succ_end(); SI != SE; ++SI)
391 WorkList.push_back(*SI);
393 while (!WorkList.empty()) {
394 MachineBasicBlock *MBB = WorkList.back();
396 if (Processed.count(MBB))
398 SlotIndex Idx = LIs->getMBBStartIdx(MBB);
399 LR = CurrLI->getLiveRangeContaining(Idx);
400 if (LR && LR->valno == ValNo) {
401 EndIdx = LIs->getMBBEndIdx(MBB);
402 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
403 // Spill slot live interval stops at the restore.
404 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
405 CurrSLI->addRange(SLR);
406 } else if (LR->end > EndIdx) {
407 // Live range extends beyond end of mbb, process successors.
408 LiveRange SLR(Idx, EndIdx.getNextIndex(), CurrSValNo);
409 CurrSLI->addRange(SLR);
410 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
411 SE = MBB->succ_end(); SI != SE; ++SI)
412 WorkList.push_back(*SI);
414 LiveRange SLR(Idx, LR->end, CurrSValNo);
415 CurrSLI->addRange(SLR);
417 Processed.insert(MBB);
422 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
423 /// construction algorithm to compute the ranges and valnos for an interval.
425 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
426 MachineBasicBlock* MBB, LiveInterval* LI,
427 SmallPtrSet<MachineInstr*, 4>& Visited,
428 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
429 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
430 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
431 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
432 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
433 bool IsTopLevel, bool IsIntraBlock) {
434 // Return memoized result if it's available.
435 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
437 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
439 else if (!IsIntraBlock && LiveOut.count(MBB))
442 // Check if our block contains any uses or defs.
443 bool ContainsDefs = Defs.count(MBB);
444 bool ContainsUses = Uses.count(MBB);
448 // Enumerate the cases of use/def contaning blocks.
449 if (!ContainsDefs && !ContainsUses) {
450 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
451 NewVNs, LiveOut, Phis,
452 IsTopLevel, IsIntraBlock);
453 } else if (ContainsDefs && !ContainsUses) {
454 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
456 // Search for the def in this block. If we don't find it before the
457 // instruction we care about, go to the fallback case. Note that that
458 // should never happen: this cannot be intrablock, so use should
459 // always be an end() iterator.
460 assert(UseI == MBB->end() && "No use marked in intrablock");
462 MachineBasicBlock::iterator Walker = UseI;
464 while (Walker != MBB->begin()) {
465 if (BlockDefs.count(Walker))
470 // Once we've found it, extend its VNInfo to our instruction.
471 SlotIndex DefIndex = LIs->getInstructionIndex(Walker);
472 DefIndex = DefIndex.getDefIndex();
473 SlotIndex EndIndex = LIs->getMBBEndIdx(MBB);
475 RetVNI = NewVNs[Walker];
476 LI->addRange(LiveRange(DefIndex, EndIndex.getNextSlot(), RetVNI));
477 } else if (!ContainsDefs && ContainsUses) {
478 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
480 // Search for the use in this block that precedes the instruction we care
481 // about, going to the fallback case if we don't find it.
482 if (UseI == MBB->begin())
483 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
484 Uses, NewVNs, LiveOut, Phis,
485 IsTopLevel, IsIntraBlock);
487 MachineBasicBlock::iterator Walker = UseI;
490 while (Walker != MBB->begin()) {
491 if (BlockUses.count(Walker)) {
498 // Must check begin() too.
500 if (BlockUses.count(Walker))
503 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
504 Uses, NewVNs, LiveOut, Phis,
505 IsTopLevel, IsIntraBlock);
508 SlotIndex UseIndex = LIs->getInstructionIndex(Walker);
509 UseIndex = UseIndex.getUseIndex();
512 EndIndex = LIs->getInstructionIndex(UseI);
513 EndIndex = EndIndex.getUseIndex();
515 EndIndex = LIs->getMBBEndIdx(MBB);
517 // Now, recursively phi construct the VNInfo for the use we found,
518 // and then extend it to include the instruction we care about
519 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
520 NewVNs, LiveOut, Phis, false, true);
522 LI->addRange(LiveRange(UseIndex, EndIndex.getNextSlot(), RetVNI));
524 // FIXME: Need to set kills properly for inter-block stuff.
525 if (RetVNI->isKill(UseIndex)) RetVNI->removeKill(UseIndex);
527 RetVNI->addKill(EndIndex);
528 } else if (ContainsDefs && ContainsUses) {
529 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
530 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
532 // This case is basically a merging of the two preceding case, with the
533 // special note that checking for defs must take precedence over checking
534 // for uses, because of two-address instructions.
536 if (UseI == MBB->begin())
537 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
538 NewVNs, LiveOut, Phis,
539 IsTopLevel, IsIntraBlock);
541 MachineBasicBlock::iterator Walker = UseI;
543 bool foundDef = false;
544 bool foundUse = false;
545 while (Walker != MBB->begin()) {
546 if (BlockDefs.count(Walker)) {
549 } else if (BlockUses.count(Walker)) {
556 // Must check begin() too.
557 if (!foundDef && !foundUse) {
558 if (BlockDefs.count(Walker))
560 else if (BlockUses.count(Walker))
563 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
564 Uses, NewVNs, LiveOut, Phis,
565 IsTopLevel, IsIntraBlock);
568 SlotIndex StartIndex = LIs->getInstructionIndex(Walker);
569 StartIndex = foundDef ? StartIndex.getDefIndex() : StartIndex.getUseIndex();
572 EndIndex = LIs->getInstructionIndex(UseI);
573 EndIndex = EndIndex.getUseIndex();
575 EndIndex = LIs->getMBBEndIdx(MBB);
578 RetVNI = NewVNs[Walker];
580 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
581 NewVNs, LiveOut, Phis, false, true);
583 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
585 if (foundUse && RetVNI->isKill(StartIndex))
586 RetVNI->removeKill(StartIndex);
588 RetVNI->addKill(EndIndex);
592 // Memoize results so we don't have to recompute them.
593 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
595 if (!NewVNs.count(UseI))
596 NewVNs[UseI] = RetVNI;
597 Visited.insert(UseI);
603 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
606 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
607 MachineBasicBlock* MBB, LiveInterval* LI,
608 SmallPtrSet<MachineInstr*, 4>& Visited,
609 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
610 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
611 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
612 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
613 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
614 bool IsTopLevel, bool IsIntraBlock) {
615 // NOTE: Because this is the fallback case from other cases, we do NOT
616 // assume that we are not intrablock here.
617 if (Phis.count(MBB)) return Phis[MBB];
619 SlotIndex StartIndex = LIs->getMBBStartIdx(MBB);
620 VNInfo *RetVNI = Phis[MBB] =
621 LI->getNextValue(SlotIndex(), /*FIXME*/ 0, false,
622 LIs->getVNInfoAllocator());
624 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
626 // If there are no uses or defs between our starting point and the
627 // beginning of the block, then recursive perform phi construction
628 // on our predecessors.
629 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
630 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
631 PE = MBB->pred_end(); PI != PE; ++PI) {
632 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
633 Visited, Defs, Uses, NewVNs,
634 LiveOut, Phis, false, false);
636 IncomingVNs[*PI] = Incoming;
639 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill()) {
640 VNInfo* OldVN = RetVNI;
641 VNInfo* NewVN = IncomingVNs.begin()->second;
642 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
643 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
645 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
646 LOE = LiveOut.end(); LOI != LOE; ++LOI)
647 if (LOI->second == OldVN)
648 LOI->second = MergedVN;
649 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
650 NVE = NewVNs.end(); NVI != NVE; ++NVI)
651 if (NVI->second == OldVN)
652 NVI->second = MergedVN;
653 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
654 PE = Phis.end(); PI != PE; ++PI)
655 if (PI->second == OldVN)
656 PI->second = MergedVN;
659 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
660 // VNInfo to represent the joined value.
661 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
662 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
663 I->second->setHasPHIKill(true);
664 SlotIndex KillIndex = LIs->getMBBEndIdx(I->first);
665 if (!I->second->isKill(KillIndex))
666 I->second->addKill(KillIndex);
672 EndIndex = LIs->getInstructionIndex(UseI);
673 EndIndex = EndIndex.getUseIndex();
675 EndIndex = LIs->getMBBEndIdx(MBB);
676 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
678 RetVNI->addKill(EndIndex);
680 // Memoize results so we don't have to recompute them.
682 LiveOut[MBB] = RetVNI;
684 if (!NewVNs.count(UseI))
685 NewVNs[UseI] = RetVNI;
686 Visited.insert(UseI);
692 /// ReconstructLiveInterval - Recompute a live interval from scratch.
693 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
694 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
696 // Clear the old ranges and valnos;
699 // Cache the uses and defs of the register
700 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
703 // Keep track of the new VNs we're creating.
704 DenseMap<MachineInstr*, VNInfo*> NewVNs;
705 SmallPtrSet<VNInfo*, 2> PhiVNs;
707 // Cache defs, and create a new VNInfo for each def.
708 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
709 DE = MRI->def_end(); DI != DE; ++DI) {
710 Defs[(*DI).getParent()].insert(&*DI);
712 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
713 DefIdx = DefIdx.getDefIndex();
715 assert(DI->getOpcode() != TargetInstrInfo::PHI &&
716 "PHI instr in code during pre-alloc splitting.");
717 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, true, Alloc);
719 // If the def is a move, set the copy field.
720 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
721 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
722 if (DstReg == LI->reg)
723 NewVN->setCopy(&*DI);
725 NewVNs[&*DI] = NewVN;
728 // Cache uses as a separate pass from actually processing them.
729 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
730 UE = MRI->use_end(); UI != UE; ++UI)
731 Uses[(*UI).getParent()].insert(&*UI);
733 // Now, actually process every use and use a phi construction algorithm
734 // to walk from it to its reaching definitions, building VNInfos along
736 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
737 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
738 SmallPtrSet<MachineInstr*, 4> Visited;
739 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
740 UE = MRI->use_end(); UI != UE; ++UI) {
741 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
742 Uses, NewVNs, LiveOut, Phis, true, true);
745 // Add ranges for dead defs
746 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
747 DE = MRI->def_end(); DI != DE; ++DI) {
748 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
749 DefIdx = DefIdx.getDefIndex();
751 if (LI->liveAt(DefIdx)) continue;
753 VNInfo* DeadVN = NewVNs[&*DI];
754 LI->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), DeadVN));
755 DeadVN->addKill(DefIdx);
758 // Update kill markers.
759 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
762 for (unsigned i = 0, e = VNI->kills.size(); i != e; ++i) {
763 SlotIndex KillIdx = VNI->kills[i];
766 MachineInstr *KillMI = LIs->getInstructionFromIndex(KillIdx);
768 MachineOperand *KillMO = KillMI->findRegisterUseOperand(CurrLI->reg);
770 // It could be a dead def.
777 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
778 /// be allocated to a different register. This function creates a new vreg,
779 /// copies the valno and its live ranges over to the new vreg's interval,
780 /// removes them from the old interval, and rewrites all uses and defs of
781 /// the original reg to the new vreg within those ranges.
782 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
783 SmallVector<VNInfo*, 4> Stack;
784 SmallVector<VNInfo*, 4> VNsToCopy;
787 // Walk through and copy the valno we care about, and any other valnos
788 // that are two-address redefinitions of the one we care about. These
789 // will need to be rewritten as well. We also check for safety of the
790 // renumbering here, by making sure that none of the valno involved has
792 while (!Stack.empty()) {
793 VNInfo* OldVN = Stack.back();
796 // Bail out if we ever encounter a valno that has a PHI kill. We can't
798 if (OldVN->hasPHIKill()) return;
800 VNsToCopy.push_back(OldVN);
802 // Locate two-address redefinitions
803 for (VNInfo::KillSet::iterator KI = OldVN->kills.begin(),
804 KE = OldVN->kills.end(); KI != KE; ++KI) {
805 assert(!KI->isPHI() &&
806 "VN previously reported having no PHI kills.");
807 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
808 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
809 if (DefIdx == ~0U) continue;
810 if (MI->isRegTiedToUseOperand(DefIdx)) {
812 CurrLI->findDefinedVNInfoForRegInt(KI->getDefIndex());
813 if (NextVN == OldVN) continue;
814 Stack.push_back(NextVN);
819 // Create the new vreg
820 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
822 // Create the new live interval
823 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
825 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
826 VNsToCopy.end(); OI != OE; ++OI) {
829 // Copy the valno over
830 VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
831 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
833 // Remove the valno from the old interval
834 CurrLI->removeValNo(OldVN);
837 // Rewrite defs and uses. This is done in two stages to avoid invalidating
839 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
841 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
842 E = MRI->reg_end(); I != E; ++I) {
843 MachineOperand& MO = I.getOperand();
844 SlotIndex InstrIdx = LIs->getInstructionIndex(&*I);
846 if ((MO.isUse() && NewLI.liveAt(InstrIdx.getUseIndex())) ||
847 (MO.isDef() && NewLI.liveAt(InstrIdx.getDefIndex())))
848 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
851 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
852 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
853 MachineInstr* Inst = I->first;
854 unsigned OpIdx = I->second;
855 MachineOperand& MO = Inst->getOperand(OpIdx);
859 // Grow the VirtRegMap, since we've created a new vreg.
862 // The renumbered vreg shares a stack slot with the old register.
863 if (IntervalSSMap.count(CurrLI->reg))
864 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
869 bool PreAllocSplitting::Rematerialize(unsigned VReg, VNInfo* ValNo,
871 MachineBasicBlock::iterator RestorePt,
872 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
873 MachineBasicBlock& MBB = *RestorePt->getParent();
875 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
876 if (!ValNo->isDefAccurate() || DefMI->getParent() == BarrierMBB)
877 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
879 KillPt = next(MachineBasicBlock::iterator(DefMI));
881 if (KillPt == DefMI->getParent()->end())
884 TII->reMaterialize(MBB, RestorePt, VReg, 0, DefMI);
885 SlotIndex RematIdx = LIs->InsertMachineInstrInMaps(prior(RestorePt));
887 ReconstructLiveInterval(CurrLI);
888 RematIdx = RematIdx.getDefIndex();
889 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RematIdx));
896 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
897 const TargetRegisterClass* RC,
899 MachineInstr* Barrier,
900 MachineBasicBlock* MBB,
902 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
903 MachineBasicBlock::iterator Pt = MBB->begin();
905 // Go top down if RefsInMBB is empty.
906 if (RefsInMBB.empty())
909 MachineBasicBlock::iterator FoldPt = Barrier;
910 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
911 !RefsInMBB.count(FoldPt))
914 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
918 SmallVector<unsigned, 1> Ops;
919 Ops.push_back(OpIdx);
921 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
924 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
925 if (I != IntervalSSMap.end()) {
928 SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
931 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
935 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
936 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
939 IntervalSSMap[vreg] = SS;
940 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
941 if (CurrSLI->hasAtLeastOneValue())
942 CurrSValNo = CurrSLI->getValNumInfo(0);
944 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
945 LSs->getVNInfoAllocator());
951 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
952 const TargetRegisterClass* RC,
953 MachineInstr* Barrier,
954 MachineBasicBlock* MBB,
956 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
957 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
960 // Go top down if RefsInMBB is empty.
961 if (RefsInMBB.empty())
964 // Can't fold a restore between a call stack setup and teardown.
965 MachineBasicBlock::iterator FoldPt = Barrier;
967 // Advance from barrier to call frame teardown.
968 while (FoldPt != MBB->getFirstTerminator() &&
969 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
970 if (RefsInMBB.count(FoldPt))
976 if (FoldPt == MBB->getFirstTerminator())
981 // Now find the restore point.
982 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
983 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
984 while (FoldPt != MBB->getFirstTerminator() &&
985 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
986 if (RefsInMBB.count(FoldPt))
992 if (FoldPt == MBB->getFirstTerminator())
999 if (FoldPt == MBB->getFirstTerminator())
1002 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1006 SmallVector<unsigned, 1> Ops;
1007 Ops.push_back(OpIdx);
1009 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1012 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1016 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1017 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1024 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1025 /// so it would not cross the barrier that's being processed. Shrink wrap
1026 /// (minimize) the live interval to the last uses.
1027 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1028 DEBUG(errs() << "Pre-alloc splitting " << LI->reg << " for " << *Barrier
1033 // Find live range where current interval cross the barrier.
1034 LiveInterval::iterator LR =
1035 CurrLI->FindLiveRangeContaining(BarrierIdx.getUseIndex());
1036 VNInfo *ValNo = LR->valno;
1038 assert(!ValNo->isUnused() && "Val# is defined by a dead def?");
1040 MachineInstr *DefMI = ValNo->isDefAccurate()
1041 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1043 // If this would create a new join point, do not split.
1044 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent())) {
1045 DEBUG(errs() << "FAILED (would create a new join point).\n");
1049 // Find all references in the barrier mbb.
1050 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1051 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1052 E = MRI->reg_end(); I != E; ++I) {
1053 MachineInstr *RefMI = &*I;
1054 if (RefMI->getParent() == BarrierMBB)
1055 RefsInMBB.insert(RefMI);
1058 // Find a point to restore the value after the barrier.
1059 MachineBasicBlock::iterator RestorePt =
1060 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB);
1061 if (RestorePt == BarrierMBB->end()) {
1062 DEBUG(errs() << "FAILED (could not find a suitable restore point).\n");
1066 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1067 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt, RefsInMBB)) {
1068 DEBUG(errs() << "success (remat).\n");
1072 // Add a spill either before the barrier or after the definition.
1073 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1074 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1075 SlotIndex SpillIndex;
1076 MachineInstr *SpillMI = NULL;
1078 if (!ValNo->isDefAccurate()) {
1079 // If we don't know where the def is we must split just before the barrier.
1080 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1081 BarrierMBB, SS, RefsInMBB))) {
1082 SpillIndex = LIs->getInstructionIndex(SpillMI);
1084 MachineBasicBlock::iterator SpillPt =
1085 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
1086 if (SpillPt == BarrierMBB->begin()) {
1087 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1088 return false; // No gap to insert spill.
1092 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1093 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1094 SpillMI = prior(SpillPt);
1095 SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1097 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1098 LIs->getZeroIndex(), SpillIndex, SS)) {
1099 // If it's already split, just restore the value. There is no need to spill
1102 DEBUG(errs() << "FAILED (def is dead).\n");
1103 return false; // Def is dead. Do nothing.
1106 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1107 BarrierMBB, SS, RefsInMBB))) {
1108 SpillIndex = LIs->getInstructionIndex(SpillMI);
1110 // Check if it's possible to insert a spill after the def MI.
1111 MachineBasicBlock::iterator SpillPt;
1112 if (DefMBB == BarrierMBB) {
1113 // Add spill after the def and the last use before the barrier.
1114 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1116 if (SpillPt == DefMBB->begin()) {
1117 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1118 return false; // No gap to insert spill.
1121 SpillPt = next(MachineBasicBlock::iterator(DefMI));
1122 if (SpillPt == DefMBB->end()) {
1123 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1124 return false; // No gap to insert spill.
1128 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1129 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg, false, SS, RC);
1130 SpillMI = prior(SpillPt);
1131 SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1135 // Remember def instruction index to spill index mapping.
1136 if (DefMI && SpillMI)
1137 Def2SpillMap[ValNo->def] = SpillIndex;
1140 bool FoldedRestore = false;
1141 SlotIndex RestoreIndex;
1142 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1143 BarrierMBB, SS, RefsInMBB)) {
1145 RestoreIndex = LIs->getInstructionIndex(RestorePt);
1146 FoldedRestore = true;
1148 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1149 MachineInstr *LoadMI = prior(RestorePt);
1150 RestoreIndex = LIs->InsertMachineInstrInMaps(LoadMI);
1153 // Update spill stack slot live interval.
1154 UpdateSpillSlotInterval(ValNo, SpillIndex.getUseIndex().getNextSlot(),
1155 RestoreIndex.getDefIndex());
1157 ReconstructLiveInterval(CurrLI);
1159 if (!FoldedRestore) {
1160 SlotIndex RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1161 RestoreIdx = RestoreIdx.getDefIndex();
1162 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RestoreIdx));
1166 DEBUG(errs() << "success.\n");
1170 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1171 /// barrier that's being processed.
1173 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1174 SmallPtrSet<LiveInterval*, 8>& Split) {
1175 // First find all the virtual registers whose live intervals are intercepted
1176 // by the current barrier.
1177 SmallVector<LiveInterval*, 8> Intervals;
1178 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1179 // FIXME: If it's not safe to move any instruction that defines the barrier
1180 // register class, then it means there are some special dependencies which
1181 // codegen is not modelling. Ignore these barriers for now.
1182 if (!TII->isSafeToMoveRegClassDefs(*RC))
1184 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1185 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1186 unsigned Reg = VRs[i];
1187 if (!LIs->hasInterval(Reg))
1189 LiveInterval *LI = &LIs->getInterval(Reg);
1190 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1191 // Virtual register live interval is intercepted by the barrier. We
1192 // should split and shrink wrap its interval if possible.
1193 Intervals.push_back(LI);
1197 // Process the affected live intervals.
1198 bool Change = false;
1199 while (!Intervals.empty()) {
1200 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1202 LiveInterval *LI = Intervals.back();
1203 Intervals.pop_back();
1204 bool result = SplitRegLiveInterval(LI);
1205 if (result) Split.insert(LI);
1212 unsigned PreAllocSplitting::getNumberOfNonSpills(
1213 SmallPtrSet<MachineInstr*, 4>& MIs,
1214 unsigned Reg, int FrameIndex,
1215 bool& FeedsTwoAddr) {
1216 unsigned NonSpills = 0;
1217 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1219 int StoreFrameIndex;
1220 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1221 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1224 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1225 if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1226 FeedsTwoAddr = true;
1232 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1233 /// split, and see if any of the spills are unnecessary. If so, remove them.
1234 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1235 bool changed = false;
1237 // Walk over all of the live intervals that were touched by the splitter,
1238 // and see if we can do any DCE and/or folding.
1239 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1240 LE = split.end(); LI != LE; ++LI) {
1241 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1243 // First, collect all the uses of the vreg, and sort them by their
1244 // reaching definition (VNInfo).
1245 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1246 UE = MRI->use_end(); UI != UE; ++UI) {
1247 SlotIndex index = LIs->getInstructionIndex(&*UI);
1248 index = index.getUseIndex();
1250 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1251 VNUseCount[LR->valno].insert(&*UI);
1254 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1255 // and/or fold them away.
1256 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1257 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1259 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1262 VNInfo* CurrVN = *VI;
1264 // We don't currently try to handle definitions with PHI kills, because
1265 // it would involve processing more than one VNInfo at once.
1266 if (CurrVN->hasPHIKill()) continue;
1268 // We also don't try to handle the results of PHI joins, since there's
1269 // no defining instruction to analyze.
1270 if (!CurrVN->isDefAccurate() || CurrVN->isUnused()) continue;
1272 // We're only interested in eliminating cruft introduced by the splitter,
1273 // is of the form load-use or load-use-store. First, check that the
1274 // definition is a load, and remember what stack slot we loaded it from.
1275 MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1277 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1279 // If the definition has no uses at all, just DCE it.
1280 if (VNUseCount[CurrVN].size() == 0) {
1281 LIs->RemoveMachineInstrFromMaps(DefMI);
1282 (*LI)->removeValNo(CurrVN);
1283 DefMI->eraseFromParent();
1284 VNUseCount.erase(CurrVN);
1290 // Second, get the number of non-store uses of the definition, as well as
1291 // a flag indicating whether it feeds into a later two-address definition.
1292 bool FeedsTwoAddr = false;
1293 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1294 (*LI)->reg, FrameIndex,
1297 // If there's one non-store use and it doesn't feed a two-addr, then
1298 // this is a load-use-store case that we can try to fold.
1299 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1300 // Start by finding the non-store use MachineInstr.
1301 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1302 int StoreFrameIndex;
1303 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1304 while (UI != VNUseCount[CurrVN].end() &&
1305 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1307 if (UI != VNUseCount[CurrVN].end())
1308 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1310 if (UI == VNUseCount[CurrVN].end()) continue;
1312 MachineInstr* use = *UI;
1314 // Attempt to fold it away!
1315 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1316 if (OpIdx == -1) continue;
1317 SmallVector<unsigned, 1> Ops;
1318 Ops.push_back(OpIdx);
1319 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1321 MachineInstr* NewMI =
1322 TII->foldMemoryOperand(*use->getParent()->getParent(),
1323 use, Ops, FrameIndex);
1325 if (!NewMI) continue;
1327 // Update relevant analyses.
1328 LIs->RemoveMachineInstrFromMaps(DefMI);
1329 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1330 (*LI)->removeValNo(CurrVN);
1332 DefMI->eraseFromParent();
1333 MachineBasicBlock* MBB = use->getParent();
1334 NewMI = MBB->insert(MBB->erase(use), NewMI);
1335 VNUseCount[CurrVN].erase(use);
1337 // Remove deleted instructions. Note that we need to remove them from
1338 // the VNInfo->use map as well, just to be safe.
1339 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1340 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1342 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1343 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1345 if (VNI->first != CurrVN)
1346 VNI->second.erase(*II);
1347 LIs->RemoveMachineInstrFromMaps(*II);
1348 (*II)->eraseFromParent();
1351 VNUseCount.erase(CurrVN);
1353 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1354 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1355 if (VI->second.erase(use))
1356 VI->second.insert(NewMI);
1363 // If there's more than one non-store instruction, we can't profitably
1364 // fold it, so bail.
1365 if (NonSpillCount) continue;
1367 // Otherwise, this is a load-store case, so DCE them.
1368 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1369 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1371 LIs->RemoveMachineInstrFromMaps(*UI);
1372 (*UI)->eraseFromParent();
1375 VNUseCount.erase(CurrVN);
1377 LIs->RemoveMachineInstrFromMaps(DefMI);
1378 (*LI)->removeValNo(CurrVN);
1379 DefMI->eraseFromParent();
1388 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1389 MachineBasicBlock* DefMBB,
1390 MachineBasicBlock* BarrierMBB) {
1391 if (DefMBB == BarrierMBB)
1394 if (LR->valno->hasPHIKill())
1397 SlotIndex MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1398 if (LR->end < MBBEnd)
1401 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1402 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1405 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1406 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1407 typedef std::pair<MachineBasicBlock*,
1408 MachineBasicBlock::succ_iterator> ItPair;
1409 SmallVector<ItPair, 4> Stack;
1410 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1412 while (!Stack.empty()) {
1413 ItPair P = Stack.back();
1416 MachineBasicBlock* PredMBB = P.first;
1417 MachineBasicBlock::succ_iterator S = P.second;
1419 if (S == PredMBB->succ_end())
1421 else if (Visited.count(*S)) {
1422 Stack.push_back(std::make_pair(PredMBB, ++S));
1425 Stack.push_back(std::make_pair(PredMBB, S+1));
1427 MachineBasicBlock* MBB = *S;
1428 Visited.insert(MBB);
1430 if (MBB == BarrierMBB)
1433 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1434 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1435 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1437 if (MDTN == DefMDTN)
1439 else if (MDTN == BarrierMDTN)
1441 MDTN = MDTN->getIDom();
1444 MBBEnd = LIs->getMBBEndIdx(MBB);
1445 if (LR->end > MBBEnd)
1446 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1453 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1455 TM = &MF.getTarget();
1456 TRI = TM->getRegisterInfo();
1457 TII = TM->getInstrInfo();
1458 MFI = MF.getFrameInfo();
1459 MRI = &MF.getRegInfo();
1460 SIs = &getAnalysis<SlotIndexes>();
1461 LIs = &getAnalysis<LiveIntervals>();
1462 LSs = &getAnalysis<LiveStacks>();
1463 VRM = &getAnalysis<VirtRegMap>();
1465 bool MadeChange = false;
1467 // Make sure blocks are numbered in order.
1468 MF.RenumberBlocks();
1470 MachineBasicBlock *Entry = MF.begin();
1471 SmallPtrSet<MachineBasicBlock*,16> Visited;
1473 SmallPtrSet<LiveInterval*, 8> Split;
1475 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1476 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1479 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1480 E = BarrierMBB->end(); I != E; ++I) {
1482 const TargetRegisterClass **BarrierRCs =
1483 Barrier->getDesc().getRegClassBarriers();
1486 BarrierIdx = LIs->getInstructionIndex(Barrier);
1487 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1491 MadeChange |= removeDeadSpills(Split);