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), cl::Hidden);
43 static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1), cl::Hidden);
45 STATISTIC(NumSplits, "Number of intervals split");
46 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
47 STATISTIC(NumFolds, "Number of intervals split with spill folding");
48 STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
49 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
50 STATISTIC(NumDeadSpills, "Number of dead spills removed");
53 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
54 MachineFunction *CurrMF;
55 const TargetMachine *TM;
56 const TargetInstrInfo *TII;
57 const TargetRegisterInfo* TRI;
58 MachineFrameInfo *MFI;
59 MachineRegisterInfo *MRI;
64 // Barrier - Current barrier being processed.
65 MachineInstr *Barrier;
67 // BarrierMBB - Basic block where the barrier resides in.
68 MachineBasicBlock *BarrierMBB;
70 // Barrier - Current barrier index.
73 // CurrLI - Current live interval being split.
76 // CurrSLI - Current stack slot live interval.
77 LiveInterval *CurrSLI;
79 // CurrSValNo - Current val# for the stack slot live interval.
82 // IntervalSSMap - A map from live interval to spill slots.
83 DenseMap<unsigned, int> IntervalSSMap;
85 // Def2SpillMap - A map from a def instruction index to spill index.
86 DenseMap<unsigned, unsigned> Def2SpillMap;
90 PreAllocSplitting() : MachineFunctionPass(&ID) {}
92 virtual bool runOnMachineFunction(MachineFunction &MF);
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95 AU.addRequired<LiveIntervals>();
96 AU.addPreserved<LiveIntervals>();
97 AU.addRequired<LiveStacks>();
98 AU.addPreserved<LiveStacks>();
99 AU.addPreserved<RegisterCoalescer>();
101 AU.addPreservedID(StrongPHIEliminationID);
103 AU.addPreservedID(PHIEliminationID);
104 AU.addRequired<MachineDominatorTree>();
105 AU.addRequired<MachineLoopInfo>();
106 AU.addRequired<VirtRegMap>();
107 AU.addPreserved<MachineDominatorTree>();
108 AU.addPreserved<MachineLoopInfo>();
109 AU.addPreserved<VirtRegMap>();
110 MachineFunctionPass::getAnalysisUsage(AU);
113 virtual void releaseMemory() {
114 IntervalSSMap.clear();
115 Def2SpillMap.clear();
118 virtual const char *getPassName() const {
119 return "Pre-Register Allocaton Live Interval Splitting";
122 /// print - Implement the dump method.
123 virtual void print(std::ostream &O, const Module* M = 0) const {
127 void print(std::ostream *O, const Module* M = 0) const {
132 MachineBasicBlock::iterator
133 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
136 MachineBasicBlock::iterator
137 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
138 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
140 MachineBasicBlock::iterator
141 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
142 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
144 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
146 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
147 unsigned&, int&) const;
149 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
151 bool SplitRegLiveInterval(LiveInterval*);
153 bool SplitRegLiveIntervals(const TargetRegisterClass **,
154 SmallPtrSet<LiveInterval*, 8>&);
156 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
157 MachineBasicBlock* BarrierMBB);
158 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
160 MachineBasicBlock::iterator RestorePt,
162 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
163 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
165 MachineInstr* Barrier,
166 MachineBasicBlock* MBB,
168 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
169 MachineInstr* FoldRestore(unsigned vreg,
170 const TargetRegisterClass* RC,
171 MachineInstr* Barrier,
172 MachineBasicBlock* MBB,
174 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
175 void RenumberValno(VNInfo* VN);
176 void ReconstructLiveInterval(LiveInterval* LI);
177 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
178 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
179 unsigned Reg, int FrameIndex, bool& TwoAddr);
180 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
181 MachineBasicBlock* MBB, LiveInterval* LI,
182 SmallPtrSet<MachineInstr*, 4>& Visited,
183 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
184 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
185 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
186 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
187 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
188 bool IsTopLevel, bool IsIntraBlock);
189 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
190 MachineBasicBlock* MBB, LiveInterval* LI,
191 SmallPtrSet<MachineInstr*, 4>& Visited,
192 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
193 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
194 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
195 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
196 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
197 bool IsTopLevel, bool IsIntraBlock);
199 } // end anonymous namespace
201 char PreAllocSplitting::ID = 0;
203 static RegisterPass<PreAllocSplitting>
204 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
206 const PassInfo *const llvm::PreAllocSplittingID = &X;
209 /// findNextEmptySlot - Find a gap after the given machine instruction in the
210 /// instruction index map. If there isn't one, return end().
211 MachineBasicBlock::iterator
212 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
213 unsigned &SpotIndex) {
214 MachineBasicBlock::iterator MII = MI;
215 if (++MII != MBB->end()) {
216 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
225 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
226 /// for spilling the current live interval. The index must be before any
227 /// defs and uses of the live interval register in the mbb. Return begin() if
229 MachineBasicBlock::iterator
230 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
232 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
233 unsigned &SpillIndex) {
234 MachineBasicBlock::iterator Pt = MBB->begin();
236 MachineBasicBlock::iterator MII = MI;
237 MachineBasicBlock::iterator EndPt = DefMI
238 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
240 while (MII != EndPt && !RefsInMBB.count(MII) &&
241 MII->getOpcode() != TRI->getCallFrameSetupOpcode())
243 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
245 while (MII != EndPt && !RefsInMBB.count(MII)) {
246 unsigned Index = LIs->getInstructionIndex(MII);
248 // We can't insert the spill between the barrier (a call), and its
249 // corresponding call frame setup.
250 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
251 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
258 } else if (LIs->hasGapBeforeInstr(Index)) {
260 SpillIndex = LIs->findGapBeforeInstr(Index, true);
263 if (RefsInMBB.count(MII))
273 /// findRestorePoint - Find a gap in the instruction index map that's suitable
274 /// for restoring the current live interval value. The index must be before any
275 /// uses of the live interval register in the mbb. Return end() if none is
277 MachineBasicBlock::iterator
278 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
280 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
281 unsigned &RestoreIndex) {
282 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
283 // begin index accordingly.
284 MachineBasicBlock::iterator Pt = MBB->end();
285 MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
287 // We start at the call, so walk forward until we find the call frame teardown
288 // since we can't insert restores before that. Bail if we encounter a use
290 MachineBasicBlock::iterator MII = MI;
291 if (MII == EndPt) return Pt;
293 while (MII != EndPt && !RefsInMBB.count(MII) &&
294 MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
296 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
299 // FIXME: Limit the number of instructions to examine to reduce
301 while (MII != EndPt) {
302 unsigned Index = LIs->getInstructionIndex(MII);
305 unsigned Gap = LIs->findGapBeforeInstr(Index);
307 // We can't insert a restore between the barrier (a call) and its
308 // corresponding call frame teardown.
309 if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
311 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
313 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
319 if (RefsInMBB.count(MII))
328 /// CreateSpillStackSlot - Create a stack slot for the live interval being
329 /// split. If the live interval was previously split, just reuse the same
331 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
332 const TargetRegisterClass *RC) {
334 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
335 if (I != IntervalSSMap.end()) {
338 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
339 IntervalSSMap[Reg] = SS;
342 // Create live interval for stack slot.
343 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
344 if (CurrSLI->hasAtLeastOneValue())
345 CurrSValNo = CurrSLI->getValNumInfo(0);
347 CurrSValNo = CurrSLI->getNextValue(0, 0, false, LSs->getVNInfoAllocator());
351 /// IsAvailableInStack - Return true if register is available in a split stack
352 /// slot at the specified index.
354 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
355 unsigned Reg, unsigned DefIndex,
356 unsigned RestoreIndex, unsigned &SpillIndex,
361 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
362 if (I == IntervalSSMap.end())
364 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
365 if (II == Def2SpillMap.end())
368 // If last spill of def is in the same mbb as barrier mbb (where restore will
369 // be), make sure it's not below the intended restore index.
370 // FIXME: Undo the previous spill?
371 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
372 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
376 SpillIndex = II->second;
380 /// UpdateSpillSlotInterval - Given the specified val# of the register live
381 /// interval being split, and the spill and restore indicies, update the live
382 /// interval of the spill stack slot.
384 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
385 unsigned RestoreIndex) {
386 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
387 "Expect restore in the barrier mbb");
389 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
390 if (MBB == BarrierMBB) {
391 // Intra-block spill + restore. We are done.
392 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
393 CurrSLI->addRange(SLR);
397 SmallPtrSet<MachineBasicBlock*, 4> Processed;
398 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
399 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
400 CurrSLI->addRange(SLR);
401 Processed.insert(MBB);
403 // Start from the spill mbb, figure out the extend of the spill slot's
405 SmallVector<MachineBasicBlock*, 4> WorkList;
406 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
407 if (LR->end > EndIdx)
408 // If live range extend beyond end of mbb, add successors to work list.
409 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
410 SE = MBB->succ_end(); SI != SE; ++SI)
411 WorkList.push_back(*SI);
413 while (!WorkList.empty()) {
414 MachineBasicBlock *MBB = WorkList.back();
416 if (Processed.count(MBB))
418 unsigned Idx = LIs->getMBBStartIdx(MBB);
419 LR = CurrLI->getLiveRangeContaining(Idx);
420 if (LR && LR->valno == ValNo) {
421 EndIdx = LIs->getMBBEndIdx(MBB);
422 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
423 // Spill slot live interval stops at the restore.
424 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
425 CurrSLI->addRange(SLR);
426 } else if (LR->end > EndIdx) {
427 // Live range extends beyond end of mbb, process successors.
428 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
429 CurrSLI->addRange(SLR);
430 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
431 SE = MBB->succ_end(); SI != SE; ++SI)
432 WorkList.push_back(*SI);
434 LiveRange SLR(Idx, LR->end, CurrSValNo);
435 CurrSLI->addRange(SLR);
437 Processed.insert(MBB);
442 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
443 /// construction algorithm to compute the ranges and valnos for an interval.
445 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
446 MachineBasicBlock* MBB, LiveInterval* LI,
447 SmallPtrSet<MachineInstr*, 4>& Visited,
448 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
449 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
450 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
451 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
452 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
453 bool IsTopLevel, bool IsIntraBlock) {
454 // Return memoized result if it's available.
455 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
457 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
459 else if (!IsIntraBlock && LiveOut.count(MBB))
462 // Check if our block contains any uses or defs.
463 bool ContainsDefs = Defs.count(MBB);
464 bool ContainsUses = Uses.count(MBB);
468 // Enumerate the cases of use/def contaning blocks.
469 if (!ContainsDefs && !ContainsUses) {
470 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
471 NewVNs, LiveOut, Phis,
472 IsTopLevel, IsIntraBlock);
473 } else if (ContainsDefs && !ContainsUses) {
474 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
476 // Search for the def in this block. If we don't find it before the
477 // instruction we care about, go to the fallback case. Note that that
478 // should never happen: this cannot be intrablock, so use should
479 // always be an end() iterator.
480 assert(UseI == MBB->end() && "No use marked in intrablock");
482 MachineBasicBlock::iterator Walker = UseI;
484 while (Walker != MBB->begin()) {
485 if (BlockDefs.count(Walker))
490 // Once we've found it, extend its VNInfo to our instruction.
491 unsigned DefIndex = LIs->getInstructionIndex(Walker);
492 DefIndex = LiveIntervals::getDefIndex(DefIndex);
493 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
495 RetVNI = NewVNs[Walker];
496 LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
497 } else if (!ContainsDefs && ContainsUses) {
498 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
500 // Search for the use in this block that precedes the instruction we care
501 // about, going to the fallback case if we don't find it.
502 if (UseI == MBB->begin())
503 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
504 Uses, NewVNs, LiveOut, Phis,
505 IsTopLevel, IsIntraBlock);
507 MachineBasicBlock::iterator Walker = UseI;
510 while (Walker != MBB->begin()) {
511 if (BlockUses.count(Walker)) {
518 // Must check begin() too.
520 if (BlockUses.count(Walker))
523 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
524 Uses, NewVNs, LiveOut, Phis,
525 IsTopLevel, IsIntraBlock);
528 unsigned UseIndex = LIs->getInstructionIndex(Walker);
529 UseIndex = LiveIntervals::getUseIndex(UseIndex);
530 unsigned EndIndex = 0;
532 EndIndex = LIs->getInstructionIndex(UseI);
533 EndIndex = LiveIntervals::getUseIndex(EndIndex);
535 EndIndex = LIs->getMBBEndIdx(MBB);
537 // Now, recursively phi construct the VNInfo for the use we found,
538 // and then extend it to include the instruction we care about
539 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
540 NewVNs, LiveOut, Phis, false, true);
542 LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
544 // FIXME: Need to set kills properly for inter-block stuff.
545 if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
547 LI->addKill(RetVNI, EndIndex, false);
548 } else if (ContainsDefs && ContainsUses) {
549 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
550 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
552 // This case is basically a merging of the two preceding case, with the
553 // special note that checking for defs must take precedence over checking
554 // for uses, because of two-address instructions.
556 if (UseI == MBB->begin())
557 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
558 NewVNs, LiveOut, Phis,
559 IsTopLevel, IsIntraBlock);
561 MachineBasicBlock::iterator Walker = UseI;
563 bool foundDef = false;
564 bool foundUse = false;
565 while (Walker != MBB->begin()) {
566 if (BlockDefs.count(Walker)) {
569 } else if (BlockUses.count(Walker)) {
576 // Must check begin() too.
577 if (!foundDef && !foundUse) {
578 if (BlockDefs.count(Walker))
580 else if (BlockUses.count(Walker))
583 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
584 Uses, NewVNs, LiveOut, Phis,
585 IsTopLevel, IsIntraBlock);
588 unsigned StartIndex = LIs->getInstructionIndex(Walker);
589 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
590 LiveIntervals::getUseIndex(StartIndex);
591 unsigned EndIndex = 0;
593 EndIndex = LIs->getInstructionIndex(UseI);
594 EndIndex = LiveIntervals::getUseIndex(EndIndex);
596 EndIndex = LIs->getMBBEndIdx(MBB);
599 RetVNI = NewVNs[Walker];
601 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
602 NewVNs, LiveOut, Phis, false, true);
604 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
606 if (foundUse && LI->isKill(RetVNI, StartIndex))
607 LI->removeKill(RetVNI, StartIndex);
609 LI->addKill(RetVNI, EndIndex, false);
613 // Memoize results so we don't have to recompute them.
614 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
616 if (!NewVNs.count(UseI))
617 NewVNs[UseI] = RetVNI;
618 Visited.insert(UseI);
624 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
627 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
628 MachineBasicBlock* MBB, LiveInterval* LI,
629 SmallPtrSet<MachineInstr*, 4>& Visited,
630 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
631 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
632 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
633 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
634 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
635 bool IsTopLevel, bool IsIntraBlock) {
636 // NOTE: Because this is the fallback case from other cases, we do NOT
637 // assume that we are not intrablock here.
638 if (Phis.count(MBB)) return Phis[MBB];
640 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
641 VNInfo *RetVNI = Phis[MBB] =
642 LI->getNextValue(0, /*FIXME*/ 0, false, LIs->getVNInfoAllocator());
644 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
646 // If there are no uses or defs between our starting point and the
647 // beginning of the block, then recursive perform phi construction
648 // on our predecessors.
649 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
650 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
651 PE = MBB->pred_end(); PI != PE; ++PI) {
652 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
653 Visited, Defs, Uses, NewVNs,
654 LiveOut, Phis, false, false);
656 IncomingVNs[*PI] = Incoming;
659 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill()) {
660 VNInfo* OldVN = RetVNI;
661 VNInfo* NewVN = IncomingVNs.begin()->second;
662 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
663 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
665 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
666 LOE = LiveOut.end(); LOI != LOE; ++LOI)
667 if (LOI->second == OldVN)
668 LOI->second = MergedVN;
669 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
670 NVE = NewVNs.end(); NVI != NVE; ++NVI)
671 if (NVI->second == OldVN)
672 NVI->second = MergedVN;
673 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
674 PE = Phis.end(); PI != PE; ++PI)
675 if (PI->second == OldVN)
676 PI->second = MergedVN;
679 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
680 // VNInfo to represent the joined value.
681 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
682 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
683 I->second->setHasPHIKill(true);
684 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
685 if (!LiveInterval::isKill(I->second, KillIndex))
686 LI->addKill(I->second, KillIndex, false);
690 unsigned EndIndex = 0;
692 EndIndex = LIs->getInstructionIndex(UseI);
693 EndIndex = LiveIntervals::getUseIndex(EndIndex);
695 EndIndex = LIs->getMBBEndIdx(MBB);
696 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
698 LI->addKill(RetVNI, EndIndex, false);
700 // Memoize results so we don't have to recompute them.
702 LiveOut[MBB] = RetVNI;
704 if (!NewVNs.count(UseI))
705 NewVNs[UseI] = RetVNI;
706 Visited.insert(UseI);
712 /// ReconstructLiveInterval - Recompute a live interval from scratch.
713 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
714 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
716 // Clear the old ranges and valnos;
719 // Cache the uses and defs of the register
720 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
723 // Keep track of the new VNs we're creating.
724 DenseMap<MachineInstr*, VNInfo*> NewVNs;
725 SmallPtrSet<VNInfo*, 2> PhiVNs;
727 // Cache defs, and create a new VNInfo for each def.
728 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
729 DE = MRI->def_end(); DI != DE; ++DI) {
730 Defs[(*DI).getParent()].insert(&*DI);
732 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
733 DefIdx = LiveIntervals::getDefIndex(DefIdx);
735 assert(DI->getOpcode() != TargetInstrInfo::PHI &&
736 "Following NewVN isPHIDef flag incorrect. Fix me!");
737 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, true, Alloc);
739 // If the def is a move, set the copy field.
740 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
741 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
742 if (DstReg == LI->reg)
745 NewVNs[&*DI] = NewVN;
748 // Cache uses as a separate pass from actually processing them.
749 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
750 UE = MRI->use_end(); UI != UE; ++UI)
751 Uses[(*UI).getParent()].insert(&*UI);
753 // Now, actually process every use and use a phi construction algorithm
754 // to walk from it to its reaching definitions, building VNInfos along
756 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
757 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
758 SmallPtrSet<MachineInstr*, 4> Visited;
759 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
760 UE = MRI->use_end(); UI != UE; ++UI) {
761 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
762 Uses, NewVNs, LiveOut, Phis, true, true);
765 // Add ranges for dead defs
766 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
767 DE = MRI->def_end(); DI != DE; ++DI) {
768 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
769 DefIdx = LiveIntervals::getDefIndex(DefIdx);
771 if (LI->liveAt(DefIdx)) continue;
773 VNInfo* DeadVN = NewVNs[&*DI];
774 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
775 LI->addKill(DeadVN, DefIdx, false);
779 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
780 /// be allocated to a different register. This function creates a new vreg,
781 /// copies the valno and its live ranges over to the new vreg's interval,
782 /// removes them from the old interval, and rewrites all uses and defs of
783 /// the original reg to the new vreg within those ranges.
784 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
785 SmallVector<VNInfo*, 4> Stack;
786 SmallVector<VNInfo*, 4> VNsToCopy;
789 // Walk through and copy the valno we care about, and any other valnos
790 // that are two-address redefinitions of the one we care about. These
791 // will need to be rewritten as well. We also check for safety of the
792 // renumbering here, by making sure that none of the valno involved has
794 while (!Stack.empty()) {
795 VNInfo* OldVN = Stack.back();
798 // Bail out if we ever encounter a valno that has a PHI kill. We can't
800 if (OldVN->hasPHIKill()) return;
802 VNsToCopy.push_back(OldVN);
804 // Locate two-address redefinitions
805 for (VNInfo::KillSet::iterator KI = OldVN->kills.begin(),
806 KE = OldVN->kills.end(); KI != KE; ++KI) {
807 assert(!KI->isPHIKill && "VN previously reported having no PHI kills.");
808 MachineInstr* MI = LIs->getInstructionFromIndex(KI->killIdx);
809 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
810 if (DefIdx == ~0U) continue;
811 if (MI->isRegTiedToUseOperand(DefIdx)) {
813 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(KI->killIdx));
814 if (NextVN == OldVN) continue;
815 Stack.push_back(NextVN);
820 // Create the new vreg
821 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
823 // Create the new live interval
824 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
826 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
827 VNsToCopy.end(); OI != OE; ++OI) {
830 // Copy the valno over
831 VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
832 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
834 // Remove the valno from the old interval
835 CurrLI->removeValNo(OldVN);
838 // Rewrite defs and uses. This is done in two stages to avoid invalidating
840 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
842 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
843 E = MRI->reg_end(); I != E; ++I) {
844 MachineOperand& MO = I.getOperand();
845 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
847 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
848 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
849 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
852 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
853 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
854 MachineInstr* Inst = I->first;
855 unsigned OpIdx = I->second;
856 MachineOperand& MO = Inst->getOperand(OpIdx);
860 // Grow the VirtRegMap, since we've created a new vreg.
863 // The renumbered vreg shares a stack slot with the old register.
864 if (IntervalSSMap.count(CurrLI->reg))
865 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
870 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
872 MachineBasicBlock::iterator RestorePt,
874 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
875 MachineBasicBlock& MBB = *RestorePt->getParent();
877 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
878 unsigned KillIdx = 0;
879 if (!ValNo->isDefAccurate() || DefMI->getParent() == BarrierMBB)
880 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
882 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
884 if (KillPt == DefMI->getParent()->end())
887 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
888 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
890 ReconstructLiveInterval(CurrLI);
891 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
892 RematIdx = LiveIntervals::getDefIndex(RematIdx);
893 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
900 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
901 const TargetRegisterClass* RC,
903 MachineInstr* Barrier,
904 MachineBasicBlock* MBB,
906 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
907 MachineBasicBlock::iterator Pt = MBB->begin();
909 // Go top down if RefsInMBB is empty.
910 if (RefsInMBB.empty())
913 MachineBasicBlock::iterator FoldPt = Barrier;
914 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
915 !RefsInMBB.count(FoldPt))
918 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
922 SmallVector<unsigned, 1> Ops;
923 Ops.push_back(OpIdx);
925 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
928 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
929 if (I != IntervalSSMap.end()) {
932 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
935 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
939 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
940 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
943 IntervalSSMap[vreg] = SS;
944 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
945 if (CurrSLI->hasAtLeastOneValue())
946 CurrSValNo = CurrSLI->getValNumInfo(0);
948 CurrSValNo = CurrSLI->getNextValue(0, 0, false, LSs->getVNInfoAllocator());
954 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
955 const TargetRegisterClass* RC,
956 MachineInstr* Barrier,
957 MachineBasicBlock* MBB,
959 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
960 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
963 // Go top down if RefsInMBB is empty.
964 if (RefsInMBB.empty())
967 // Can't fold a restore between a call stack setup and teardown.
968 MachineBasicBlock::iterator FoldPt = Barrier;
970 // Advance from barrier to call frame teardown.
971 while (FoldPt != MBB->getFirstTerminator() &&
972 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
973 if (RefsInMBB.count(FoldPt))
979 if (FoldPt == MBB->getFirstTerminator())
984 // Now find the restore point.
985 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
986 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
987 while (FoldPt != MBB->getFirstTerminator() &&
988 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
989 if (RefsInMBB.count(FoldPt))
995 if (FoldPt == MBB->getFirstTerminator())
1002 if (FoldPt == MBB->getFirstTerminator())
1005 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1009 SmallVector<unsigned, 1> Ops;
1010 Ops.push_back(OpIdx);
1012 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1015 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1019 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1020 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1027 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1028 /// so it would not cross the barrier that's being processed. Shrink wrap
1029 /// (minimize) the live interval to the last uses.
1030 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1033 // Find live range where current interval cross the barrier.
1034 LiveInterval::iterator LR =
1035 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
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()))
1047 // Find all references in the barrier mbb.
1048 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1049 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1050 E = MRI->reg_end(); I != E; ++I) {
1051 MachineInstr *RefMI = &*I;
1052 if (RefMI->getParent() == BarrierMBB)
1053 RefsInMBB.insert(RefMI);
1056 // Find a point to restore the value after the barrier.
1057 unsigned RestoreIndex = 0;
1058 MachineBasicBlock::iterator RestorePt =
1059 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1060 if (RestorePt == BarrierMBB->end())
1063 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1064 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1065 RestoreIndex, RefsInMBB))
1068 // Add a spill either before the barrier or after the definition.
1069 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1070 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1071 unsigned SpillIndex = 0;
1072 MachineInstr *SpillMI = NULL;
1074 if (!ValNo->isDefAccurate()) {
1075 // If we don't know where the def is we must split just before the barrier.
1076 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1077 BarrierMBB, SS, RefsInMBB))) {
1078 SpillIndex = LIs->getInstructionIndex(SpillMI);
1080 MachineBasicBlock::iterator SpillPt =
1081 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1082 if (SpillPt == BarrierMBB->begin())
1083 return false; // No gap to insert spill.
1086 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1087 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1088 SpillMI = prior(SpillPt);
1089 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1091 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1092 RestoreIndex, SpillIndex, SS)) {
1093 // If it's already split, just restore the value. There is no need to spill
1096 return false; // Def is dead. Do nothing.
1098 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1099 BarrierMBB, SS, RefsInMBB))) {
1100 SpillIndex = LIs->getInstructionIndex(SpillMI);
1102 // Check if it's possible to insert a spill after the def MI.
1103 MachineBasicBlock::iterator SpillPt;
1104 if (DefMBB == BarrierMBB) {
1105 // Add spill after the def and the last use before the barrier.
1106 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1107 RefsInMBB, SpillIndex);
1108 if (SpillPt == DefMBB->begin())
1109 return false; // No gap to insert spill.
1111 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1112 if (SpillPt == DefMBB->end())
1113 return false; // No gap to insert spill.
1115 // Add spill. The store instruction kills the register if def is before
1116 // the barrier in the barrier block.
1117 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1118 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1119 DefMBB == BarrierMBB, SS, RC);
1120 SpillMI = prior(SpillPt);
1121 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1125 // Remember def instruction index to spill index mapping.
1126 if (DefMI && SpillMI)
1127 Def2SpillMap[ValNo->def] = SpillIndex;
1130 bool FoldedRestore = false;
1131 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1132 BarrierMBB, SS, RefsInMBB)) {
1134 RestoreIndex = LIs->getInstructionIndex(RestorePt);
1135 FoldedRestore = true;
1137 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1138 MachineInstr *LoadMI = prior(RestorePt);
1139 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1142 // Update spill stack slot live interval.
1143 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1144 LIs->getDefIndex(RestoreIndex));
1146 ReconstructLiveInterval(CurrLI);
1148 if (!FoldedRestore) {
1149 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1150 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1151 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1158 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1159 /// barrier that's being processed.
1161 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1162 SmallPtrSet<LiveInterval*, 8>& Split) {
1163 // First find all the virtual registers whose live intervals are intercepted
1164 // by the current barrier.
1165 SmallVector<LiveInterval*, 8> Intervals;
1166 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1167 // FIXME: If it's not safe to move any instruction that defines the barrier
1168 // register class, then it means there are some special dependencies which
1169 // codegen is not modelling. Ignore these barriers for now.
1170 if (!TII->isSafeToMoveRegClassDefs(*RC))
1172 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1173 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1174 unsigned Reg = VRs[i];
1175 if (!LIs->hasInterval(Reg))
1177 LiveInterval *LI = &LIs->getInterval(Reg);
1178 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1179 // Virtual register live interval is intercepted by the barrier. We
1180 // should split and shrink wrap its interval if possible.
1181 Intervals.push_back(LI);
1185 // Process the affected live intervals.
1186 bool Change = false;
1187 while (!Intervals.empty()) {
1188 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1190 else if (NumSplits == 4)
1192 LiveInterval *LI = Intervals.back();
1193 Intervals.pop_back();
1194 bool result = SplitRegLiveInterval(LI);
1195 if (result) Split.insert(LI);
1202 unsigned PreAllocSplitting::getNumberOfNonSpills(
1203 SmallPtrSet<MachineInstr*, 4>& MIs,
1204 unsigned Reg, int FrameIndex,
1205 bool& FeedsTwoAddr) {
1206 unsigned NonSpills = 0;
1207 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1209 int StoreFrameIndex;
1210 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1211 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1214 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1215 if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1216 FeedsTwoAddr = true;
1222 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1223 /// split, and see if any of the spills are unnecessary. If so, remove them.
1224 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1225 bool changed = false;
1227 // Walk over all of the live intervals that were touched by the splitter,
1228 // and see if we can do any DCE and/or folding.
1229 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1230 LE = split.end(); LI != LE; ++LI) {
1231 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1233 // First, collect all the uses of the vreg, and sort them by their
1234 // reaching definition (VNInfo).
1235 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1236 UE = MRI->use_end(); UI != UE; ++UI) {
1237 unsigned index = LIs->getInstructionIndex(&*UI);
1238 index = LiveIntervals::getUseIndex(index);
1240 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1241 VNUseCount[LR->valno].insert(&*UI);
1244 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1245 // and/or fold them away.
1246 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1247 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1249 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1252 VNInfo* CurrVN = *VI;
1254 // We don't currently try to handle definitions with PHI kills, because
1255 // it would involve processing more than one VNInfo at once.
1256 if (CurrVN->hasPHIKill()) continue;
1258 // We also don't try to handle the results of PHI joins, since there's
1259 // no defining instruction to analyze.
1260 if (!CurrVN->isDefAccurate() || CurrVN->isUnused()) continue;
1262 // We're only interested in eliminating cruft introduced by the splitter,
1263 // is of the form load-use or load-use-store. First, check that the
1264 // definition is a load, and remember what stack slot we loaded it from.
1265 MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1267 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1269 // If the definition has no uses at all, just DCE it.
1270 if (VNUseCount[CurrVN].size() == 0) {
1271 LIs->RemoveMachineInstrFromMaps(DefMI);
1272 (*LI)->removeValNo(CurrVN);
1273 DefMI->eraseFromParent();
1274 VNUseCount.erase(CurrVN);
1280 // Second, get the number of non-store uses of the definition, as well as
1281 // a flag indicating whether it feeds into a later two-address definition.
1282 bool FeedsTwoAddr = false;
1283 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1284 (*LI)->reg, FrameIndex,
1287 // If there's one non-store use and it doesn't feed a two-addr, then
1288 // this is a load-use-store case that we can try to fold.
1289 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1290 // Start by finding the non-store use MachineInstr.
1291 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1292 int StoreFrameIndex;
1293 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1294 while (UI != VNUseCount[CurrVN].end() &&
1295 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1297 if (UI != VNUseCount[CurrVN].end())
1298 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1300 if (UI == VNUseCount[CurrVN].end()) continue;
1302 MachineInstr* use = *UI;
1304 // Attempt to fold it away!
1305 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1306 if (OpIdx == -1) continue;
1307 SmallVector<unsigned, 1> Ops;
1308 Ops.push_back(OpIdx);
1309 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1311 MachineInstr* NewMI =
1312 TII->foldMemoryOperand(*use->getParent()->getParent(),
1313 use, Ops, FrameIndex);
1315 if (!NewMI) continue;
1317 // Update relevant analyses.
1318 LIs->RemoveMachineInstrFromMaps(DefMI);
1319 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1320 (*LI)->removeValNo(CurrVN);
1322 DefMI->eraseFromParent();
1323 MachineBasicBlock* MBB = use->getParent();
1324 NewMI = MBB->insert(MBB->erase(use), NewMI);
1325 VNUseCount[CurrVN].erase(use);
1327 // Remove deleted instructions. Note that we need to remove them from
1328 // the VNInfo->use map as well, just to be safe.
1329 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1330 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1332 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1333 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1335 if (VNI->first != CurrVN)
1336 VNI->second.erase(*II);
1337 LIs->RemoveMachineInstrFromMaps(*II);
1338 (*II)->eraseFromParent();
1341 VNUseCount.erase(CurrVN);
1343 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1344 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1345 if (VI->second.erase(use))
1346 VI->second.insert(NewMI);
1353 // If there's more than one non-store instruction, we can't profitably
1354 // fold it, so bail.
1355 if (NonSpillCount) continue;
1357 // Otherwise, this is a load-store case, so DCE them.
1358 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1359 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1361 LIs->RemoveMachineInstrFromMaps(*UI);
1362 (*UI)->eraseFromParent();
1365 VNUseCount.erase(CurrVN);
1367 LIs->RemoveMachineInstrFromMaps(DefMI);
1368 (*LI)->removeValNo(CurrVN);
1369 DefMI->eraseFromParent();
1378 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1379 MachineBasicBlock* DefMBB,
1380 MachineBasicBlock* BarrierMBB) {
1381 if (DefMBB == BarrierMBB)
1384 if (LR->valno->hasPHIKill())
1387 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1388 if (LR->end < MBBEnd)
1391 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1392 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1395 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1396 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1397 typedef std::pair<MachineBasicBlock*,
1398 MachineBasicBlock::succ_iterator> ItPair;
1399 SmallVector<ItPair, 4> Stack;
1400 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1402 while (!Stack.empty()) {
1403 ItPair P = Stack.back();
1406 MachineBasicBlock* PredMBB = P.first;
1407 MachineBasicBlock::succ_iterator S = P.second;
1409 if (S == PredMBB->succ_end())
1411 else if (Visited.count(*S)) {
1412 Stack.push_back(std::make_pair(PredMBB, ++S));
1415 Stack.push_back(std::make_pair(PredMBB, S+1));
1417 MachineBasicBlock* MBB = *S;
1418 Visited.insert(MBB);
1420 if (MBB == BarrierMBB)
1423 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1424 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1425 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1427 if (MDTN == DefMDTN)
1429 else if (MDTN == BarrierMDTN)
1431 MDTN = MDTN->getIDom();
1434 MBBEnd = LIs->getMBBEndIdx(MBB);
1435 if (LR->end > MBBEnd)
1436 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1443 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1445 TM = &MF.getTarget();
1446 TRI = TM->getRegisterInfo();
1447 TII = TM->getInstrInfo();
1448 MFI = MF.getFrameInfo();
1449 MRI = &MF.getRegInfo();
1450 LIs = &getAnalysis<LiveIntervals>();
1451 LSs = &getAnalysis<LiveStacks>();
1452 VRM = &getAnalysis<VirtRegMap>();
1454 bool MadeChange = false;
1456 // Make sure blocks are numbered in order.
1457 MF.RenumberBlocks();
1459 MachineBasicBlock *Entry = MF.begin();
1460 SmallPtrSet<MachineBasicBlock*,16> Visited;
1462 SmallPtrSet<LiveInterval*, 8> Split;
1464 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1465 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1468 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1469 E = BarrierMBB->end(); I != E; ++I) {
1471 const TargetRegisterClass **BarrierRCs =
1472 Barrier->getDesc().getRegClassBarriers();
1475 BarrierIdx = LIs->getInstructionIndex(Barrier);
1476 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1480 MadeChange |= removeDeadSpills(Split);