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<LiveIndex, LiveIndex> Def2SpillMap;
90 PreAllocSplitting() : MachineFunctionPass(&ID) {}
92 virtual bool runOnMachineFunction(MachineFunction &MF);
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<LiveIndexes>();
97 AU.addPreserved<LiveIndexes>();
98 AU.addRequired<LiveIntervals>();
99 AU.addPreserved<LiveIntervals>();
100 AU.addRequired<LiveStacks>();
101 AU.addPreserved<LiveStacks>();
102 AU.addPreserved<RegisterCoalescer>();
104 AU.addPreservedID(StrongPHIEliminationID);
106 AU.addPreservedID(PHIEliminationID);
107 AU.addRequired<MachineDominatorTree>();
108 AU.addRequired<MachineLoopInfo>();
109 AU.addRequired<VirtRegMap>();
110 AU.addPreserved<MachineDominatorTree>();
111 AU.addPreserved<MachineLoopInfo>();
112 AU.addPreserved<VirtRegMap>();
113 MachineFunctionPass::getAnalysisUsage(AU);
116 virtual void releaseMemory() {
117 IntervalSSMap.clear();
118 Def2SpillMap.clear();
121 virtual const char *getPassName() const {
122 return "Pre-Register Allocaton Live Interval Splitting";
125 /// print - Implement the dump method.
126 virtual void print(raw_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>&, LiveIndex&);
140 MachineBasicBlock::iterator
141 findRestorePoint(MachineBasicBlock*, MachineInstr*, LiveIndex,
142 SmallPtrSet<MachineInstr*, 4>&, LiveIndex&);
144 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
146 bool IsAvailableInStack(MachineBasicBlock*, unsigned,
147 LiveIndex, LiveIndex,
148 LiveIndex&, int&) const;
150 void UpdateSpillSlotInterval(VNInfo*, LiveIndex, LiveIndex);
152 bool SplitRegLiveInterval(LiveInterval*);
154 bool SplitRegLiveIntervals(const TargetRegisterClass **,
155 SmallPtrSet<LiveInterval*, 8>&);
157 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
158 MachineBasicBlock* BarrierMBB);
159 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
161 MachineBasicBlock::iterator RestorePt,
162 LiveIndex RestoreIdx,
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;
210 /// findNextEmptySlot - Find a gap after the given machine instruction in the
211 /// instruction index map. If there isn't one, return end().
212 MachineBasicBlock::iterator
213 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
214 LiveIndex &SpotIndex) {
215 MachineBasicBlock::iterator MII = MI;
216 if (++MII != MBB->end()) {
218 LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
219 if (Index != LiveIndex()) {
227 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
228 /// for spilling the current live interval. The index must be before any
229 /// defs and uses of the live interval register in the mbb. Return begin() if
231 MachineBasicBlock::iterator
232 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
234 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
235 LiveIndex &SpillIndex) {
236 MachineBasicBlock::iterator Pt = MBB->begin();
238 MachineBasicBlock::iterator MII = MI;
239 MachineBasicBlock::iterator EndPt = DefMI
240 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
242 while (MII != EndPt && !RefsInMBB.count(MII) &&
243 MII->getOpcode() != TRI->getCallFrameSetupOpcode())
245 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
247 while (MII != EndPt && !RefsInMBB.count(MII)) {
248 LiveIndex Index = LIs->getInstructionIndex(MII);
250 // We can't insert the spill between the barrier (a call), and its
251 // corresponding call frame setup.
252 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
253 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
260 } else if (LIs->hasGapBeforeInstr(Index)) {
262 SpillIndex = LIs->findGapBeforeInstr(Index, true);
265 if (RefsInMBB.count(MII))
275 /// findRestorePoint - Find a gap in the instruction index map that's suitable
276 /// for restoring the current live interval value. The index must be before any
277 /// uses of the live interval register in the mbb. Return end() if none is
279 MachineBasicBlock::iterator
280 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
282 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
283 LiveIndex &RestoreIndex) {
284 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
285 // begin index accordingly.
286 MachineBasicBlock::iterator Pt = MBB->end();
287 MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
289 // We start at the call, so walk forward until we find the call frame teardown
290 // since we can't insert restores before that. Bail if we encounter a use
292 MachineBasicBlock::iterator MII = MI;
293 if (MII == EndPt) return Pt;
295 while (MII != EndPt && !RefsInMBB.count(MII) &&
296 MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
298 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
301 // FIXME: Limit the number of instructions to examine to reduce
303 while (MII != EndPt) {
304 LiveIndex Index = LIs->getInstructionIndex(MII);
307 LiveIndex Gap = LIs->findGapBeforeInstr(Index);
309 // We can't insert a restore between the barrier (a call) and its
310 // corresponding call frame teardown.
311 if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
313 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
315 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
316 } else if (Gap != LiveIndex()) {
321 if (RefsInMBB.count(MII))
330 /// CreateSpillStackSlot - Create a stack slot for the live interval being
331 /// split. If the live interval was previously split, just reuse the same
333 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
334 const TargetRegisterClass *RC) {
336 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
337 if (I != IntervalSSMap.end()) {
340 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
341 IntervalSSMap[Reg] = SS;
344 // Create live interval for stack slot.
345 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
346 if (CurrSLI->hasAtLeastOneValue())
347 CurrSValNo = CurrSLI->getValNumInfo(0);
349 CurrSValNo = CurrSLI->getNextValue(LiveIndex(), 0, false,
350 LSs->getVNInfoAllocator());
354 /// IsAvailableInStack - Return true if register is available in a split stack
355 /// slot at the specified index.
357 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
358 unsigned Reg, LiveIndex DefIndex,
359 LiveIndex RestoreIndex,
360 LiveIndex &SpillIndex,
365 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
366 if (I == IntervalSSMap.end())
368 DenseMap<LiveIndex, LiveIndex>::iterator
369 II = Def2SpillMap.find(DefIndex);
370 if (II == Def2SpillMap.end())
373 // If last spill of def is in the same mbb as barrier mbb (where restore will
374 // be), make sure it's not below the intended restore index.
375 // FIXME: Undo the previous spill?
376 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
377 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
381 SpillIndex = II->second;
385 /// UpdateSpillSlotInterval - Given the specified val# of the register live
386 /// interval being split, and the spill and restore indicies, update the live
387 /// interval of the spill stack slot.
389 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, LiveIndex SpillIndex,
390 LiveIndex RestoreIndex) {
391 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
392 "Expect restore in the barrier mbb");
394 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
395 if (MBB == BarrierMBB) {
396 // Intra-block spill + restore. We are done.
397 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
398 CurrSLI->addRange(SLR);
402 SmallPtrSet<MachineBasicBlock*, 4> Processed;
403 LiveIndex EndIdx = LIs->getMBBEndIdx(MBB);
404 LiveRange SLR(SpillIndex, EndIdx.getNextSlot(), CurrSValNo);
405 CurrSLI->addRange(SLR);
406 Processed.insert(MBB);
408 // Start from the spill mbb, figure out the extend of the spill slot's
410 SmallVector<MachineBasicBlock*, 4> WorkList;
411 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
412 if (LR->end > EndIdx)
413 // If live range extend beyond end of mbb, add successors to work list.
414 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
415 SE = MBB->succ_end(); SI != SE; ++SI)
416 WorkList.push_back(*SI);
418 while (!WorkList.empty()) {
419 MachineBasicBlock *MBB = WorkList.back();
421 if (Processed.count(MBB))
423 LiveIndex Idx = LIs->getMBBStartIdx(MBB);
424 LR = CurrLI->getLiveRangeContaining(Idx);
425 if (LR && LR->valno == ValNo) {
426 EndIdx = LIs->getMBBEndIdx(MBB);
427 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
428 // Spill slot live interval stops at the restore.
429 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
430 CurrSLI->addRange(SLR);
431 } else if (LR->end > EndIdx) {
432 // Live range extends beyond end of mbb, process successors.
433 LiveRange SLR(Idx, EndIdx.getNextIndex(), CurrSValNo);
434 CurrSLI->addRange(SLR);
435 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
436 SE = MBB->succ_end(); SI != SE; ++SI)
437 WorkList.push_back(*SI);
439 LiveRange SLR(Idx, LR->end, CurrSValNo);
440 CurrSLI->addRange(SLR);
442 Processed.insert(MBB);
447 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
448 /// construction algorithm to compute the ranges and valnos for an interval.
450 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
451 MachineBasicBlock* MBB, LiveInterval* LI,
452 SmallPtrSet<MachineInstr*, 4>& Visited,
453 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
454 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
455 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
456 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
457 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
458 bool IsTopLevel, bool IsIntraBlock) {
459 // Return memoized result if it's available.
460 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
462 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
464 else if (!IsIntraBlock && LiveOut.count(MBB))
467 // Check if our block contains any uses or defs.
468 bool ContainsDefs = Defs.count(MBB);
469 bool ContainsUses = Uses.count(MBB);
473 // Enumerate the cases of use/def contaning blocks.
474 if (!ContainsDefs && !ContainsUses) {
475 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
476 NewVNs, LiveOut, Phis,
477 IsTopLevel, IsIntraBlock);
478 } else if (ContainsDefs && !ContainsUses) {
479 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
481 // Search for the def in this block. If we don't find it before the
482 // instruction we care about, go to the fallback case. Note that that
483 // should never happen: this cannot be intrablock, so use should
484 // always be an end() iterator.
485 assert(UseI == MBB->end() && "No use marked in intrablock");
487 MachineBasicBlock::iterator Walker = UseI;
489 while (Walker != MBB->begin()) {
490 if (BlockDefs.count(Walker))
495 // Once we've found it, extend its VNInfo to our instruction.
496 LiveIndex DefIndex = LIs->getInstructionIndex(Walker);
497 DefIndex = DefIndex.getDefIndex();
498 LiveIndex EndIndex = LIs->getMBBEndIdx(MBB);
500 RetVNI = NewVNs[Walker];
501 LI->addRange(LiveRange(DefIndex, EndIndex.getNextSlot(), RetVNI));
502 } else if (!ContainsDefs && ContainsUses) {
503 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
505 // Search for the use in this block that precedes the instruction we care
506 // about, going to the fallback case if we don't find it.
507 if (UseI == MBB->begin())
508 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
509 Uses, NewVNs, LiveOut, Phis,
510 IsTopLevel, IsIntraBlock);
512 MachineBasicBlock::iterator Walker = UseI;
515 while (Walker != MBB->begin()) {
516 if (BlockUses.count(Walker)) {
523 // Must check begin() too.
525 if (BlockUses.count(Walker))
528 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
529 Uses, NewVNs, LiveOut, Phis,
530 IsTopLevel, IsIntraBlock);
533 LiveIndex UseIndex = LIs->getInstructionIndex(Walker);
534 UseIndex = UseIndex.getUseIndex();
537 EndIndex = LIs->getInstructionIndex(UseI);
538 EndIndex = EndIndex.getUseIndex();
540 EndIndex = LIs->getMBBEndIdx(MBB);
542 // Now, recursively phi construct the VNInfo for the use we found,
543 // and then extend it to include the instruction we care about
544 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
545 NewVNs, LiveOut, Phis, false, true);
547 LI->addRange(LiveRange(UseIndex, EndIndex.getNextSlot(), RetVNI));
549 // FIXME: Need to set kills properly for inter-block stuff.
550 if (RetVNI->isKill(UseIndex)) RetVNI->removeKill(UseIndex);
552 RetVNI->addKill(EndIndex);
553 } else if (ContainsDefs && ContainsUses) {
554 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
555 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
557 // This case is basically a merging of the two preceding case, with the
558 // special note that checking for defs must take precedence over checking
559 // for uses, because of two-address instructions.
561 if (UseI == MBB->begin())
562 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
563 NewVNs, LiveOut, Phis,
564 IsTopLevel, IsIntraBlock);
566 MachineBasicBlock::iterator Walker = UseI;
568 bool foundDef = false;
569 bool foundUse = false;
570 while (Walker != MBB->begin()) {
571 if (BlockDefs.count(Walker)) {
574 } else if (BlockUses.count(Walker)) {
581 // Must check begin() too.
582 if (!foundDef && !foundUse) {
583 if (BlockDefs.count(Walker))
585 else if (BlockUses.count(Walker))
588 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
589 Uses, NewVNs, LiveOut, Phis,
590 IsTopLevel, IsIntraBlock);
593 LiveIndex StartIndex = LIs->getInstructionIndex(Walker);
594 StartIndex = foundDef ? StartIndex.getDefIndex() : StartIndex.getUseIndex();
597 EndIndex = LIs->getInstructionIndex(UseI);
598 EndIndex = EndIndex.getUseIndex();
600 EndIndex = LIs->getMBBEndIdx(MBB);
603 RetVNI = NewVNs[Walker];
605 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
606 NewVNs, LiveOut, Phis, false, true);
608 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
610 if (foundUse && RetVNI->isKill(StartIndex))
611 RetVNI->removeKill(StartIndex);
613 RetVNI->addKill(EndIndex);
617 // Memoize results so we don't have to recompute them.
618 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
620 if (!NewVNs.count(UseI))
621 NewVNs[UseI] = RetVNI;
622 Visited.insert(UseI);
628 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
631 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
632 MachineBasicBlock* MBB, LiveInterval* LI,
633 SmallPtrSet<MachineInstr*, 4>& Visited,
634 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
635 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
636 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
637 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
638 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
639 bool IsTopLevel, bool IsIntraBlock) {
640 // NOTE: Because this is the fallback case from other cases, we do NOT
641 // assume that we are not intrablock here.
642 if (Phis.count(MBB)) return Phis[MBB];
644 LiveIndex StartIndex = LIs->getMBBStartIdx(MBB);
645 VNInfo *RetVNI = Phis[MBB] =
646 LI->getNextValue(LiveIndex(), /*FIXME*/ 0, false,
647 LIs->getVNInfoAllocator());
649 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
651 // If there are no uses or defs between our starting point and the
652 // beginning of the block, then recursive perform phi construction
653 // on our predecessors.
654 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
655 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
656 PE = MBB->pred_end(); PI != PE; ++PI) {
657 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
658 Visited, Defs, Uses, NewVNs,
659 LiveOut, Phis, false, false);
661 IncomingVNs[*PI] = Incoming;
664 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill()) {
665 VNInfo* OldVN = RetVNI;
666 VNInfo* NewVN = IncomingVNs.begin()->second;
667 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
668 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
670 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
671 LOE = LiveOut.end(); LOI != LOE; ++LOI)
672 if (LOI->second == OldVN)
673 LOI->second = MergedVN;
674 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
675 NVE = NewVNs.end(); NVI != NVE; ++NVI)
676 if (NVI->second == OldVN)
677 NVI->second = MergedVN;
678 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
679 PE = Phis.end(); PI != PE; ++PI)
680 if (PI->second == OldVN)
681 PI->second = MergedVN;
684 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
685 // VNInfo to represent the joined value.
686 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
687 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
688 I->second->setHasPHIKill(true);
689 LiveIndex KillIndex = LIs->getMBBEndIdx(I->first);
690 if (!I->second->isKill(KillIndex))
691 I->second->addKill(KillIndex);
697 EndIndex = LIs->getInstructionIndex(UseI);
698 EndIndex = EndIndex.getUseIndex();
700 EndIndex = LIs->getMBBEndIdx(MBB);
701 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
703 RetVNI->addKill(EndIndex);
705 // Memoize results so we don't have to recompute them.
707 LiveOut[MBB] = RetVNI;
709 if (!NewVNs.count(UseI))
710 NewVNs[UseI] = RetVNI;
711 Visited.insert(UseI);
717 /// ReconstructLiveInterval - Recompute a live interval from scratch.
718 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
719 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
721 // Clear the old ranges and valnos;
724 // Cache the uses and defs of the register
725 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
728 // Keep track of the new VNs we're creating.
729 DenseMap<MachineInstr*, VNInfo*> NewVNs;
730 SmallPtrSet<VNInfo*, 2> PhiVNs;
732 // Cache defs, and create a new VNInfo for each def.
733 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
734 DE = MRI->def_end(); DI != DE; ++DI) {
735 Defs[(*DI).getParent()].insert(&*DI);
737 LiveIndex DefIdx = LIs->getInstructionIndex(&*DI);
738 DefIdx = DefIdx.getDefIndex();
740 assert(DI->getOpcode() != TargetInstrInfo::PHI &&
741 "Following NewVN isPHIDef flag incorrect. Fix me!");
742 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, true, Alloc);
744 // If the def is a move, set the copy field.
745 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
746 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
747 if (DstReg == LI->reg)
748 NewVN->setCopy(&*DI);
750 NewVNs[&*DI] = NewVN;
753 // Cache uses as a separate pass from actually processing them.
754 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
755 UE = MRI->use_end(); UI != UE; ++UI)
756 Uses[(*UI).getParent()].insert(&*UI);
758 // Now, actually process every use and use a phi construction algorithm
759 // to walk from it to its reaching definitions, building VNInfos along
761 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
762 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
763 SmallPtrSet<MachineInstr*, 4> Visited;
764 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
765 UE = MRI->use_end(); UI != UE; ++UI) {
766 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
767 Uses, NewVNs, LiveOut, Phis, true, true);
770 // Add ranges for dead defs
771 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
772 DE = MRI->def_end(); DI != DE; ++DI) {
773 LiveIndex DefIdx = LIs->getInstructionIndex(&*DI);
774 DefIdx = DefIdx.getDefIndex();
776 if (LI->liveAt(DefIdx)) continue;
778 VNInfo* DeadVN = NewVNs[&*DI];
779 LI->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), DeadVN));
780 DeadVN->addKill(DefIdx);
783 // Update kill markers.
784 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
787 for (unsigned i = 0, e = VNI->kills.size(); i != e; ++i) {
788 LiveIndex KillIdx = VNI->kills[i];
791 MachineInstr *KillMI = LIs->getInstructionFromIndex(KillIdx);
793 MachineOperand *KillMO = KillMI->findRegisterUseOperand(CurrLI->reg);
795 // It could be a dead def.
802 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
803 /// be allocated to a different register. This function creates a new vreg,
804 /// copies the valno and its live ranges over to the new vreg's interval,
805 /// removes them from the old interval, and rewrites all uses and defs of
806 /// the original reg to the new vreg within those ranges.
807 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
808 SmallVector<VNInfo*, 4> Stack;
809 SmallVector<VNInfo*, 4> VNsToCopy;
812 // Walk through and copy the valno we care about, and any other valnos
813 // that are two-address redefinitions of the one we care about. These
814 // will need to be rewritten as well. We also check for safety of the
815 // renumbering here, by making sure that none of the valno involved has
817 while (!Stack.empty()) {
818 VNInfo* OldVN = Stack.back();
821 // Bail out if we ever encounter a valno that has a PHI kill. We can't
823 if (OldVN->hasPHIKill()) return;
825 VNsToCopy.push_back(OldVN);
827 // Locate two-address redefinitions
828 for (VNInfo::KillSet::iterator KI = OldVN->kills.begin(),
829 KE = OldVN->kills.end(); KI != KE; ++KI) {
830 assert(!KI->isPHI() &&
831 "VN previously reported having no PHI kills.");
832 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
833 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
834 if (DefIdx == ~0U) continue;
835 if (MI->isRegTiedToUseOperand(DefIdx)) {
837 CurrLI->findDefinedVNInfoForRegInt(KI->getDefIndex());
838 if (NextVN == OldVN) continue;
839 Stack.push_back(NextVN);
844 // Create the new vreg
845 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
847 // Create the new live interval
848 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
850 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
851 VNsToCopy.end(); OI != OE; ++OI) {
854 // Copy the valno over
855 VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
856 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
858 // Remove the valno from the old interval
859 CurrLI->removeValNo(OldVN);
862 // Rewrite defs and uses. This is done in two stages to avoid invalidating
864 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
866 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
867 E = MRI->reg_end(); I != E; ++I) {
868 MachineOperand& MO = I.getOperand();
869 LiveIndex InstrIdx = LIs->getInstructionIndex(&*I);
871 if ((MO.isUse() && NewLI.liveAt(InstrIdx.getUseIndex())) ||
872 (MO.isDef() && NewLI.liveAt(InstrIdx.getDefIndex())))
873 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
876 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
877 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
878 MachineInstr* Inst = I->first;
879 unsigned OpIdx = I->second;
880 MachineOperand& MO = Inst->getOperand(OpIdx);
884 // Grow the VirtRegMap, since we've created a new vreg.
887 // The renumbered vreg shares a stack slot with the old register.
888 if (IntervalSSMap.count(CurrLI->reg))
889 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
894 bool PreAllocSplitting::Rematerialize(unsigned VReg, VNInfo* ValNo,
896 MachineBasicBlock::iterator RestorePt,
897 LiveIndex RestoreIdx,
898 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
899 MachineBasicBlock& MBB = *RestorePt->getParent();
901 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
903 if (!ValNo->isDefAccurate() || DefMI->getParent() == BarrierMBB)
904 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
906 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
908 if (KillPt == DefMI->getParent()->end())
911 TII->reMaterialize(MBB, RestorePt, VReg, 0, DefMI);
912 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
914 ReconstructLiveInterval(CurrLI);
915 LiveIndex RematIdx = LIs->getInstructionIndex(prior(RestorePt));
916 RematIdx = RematIdx.getDefIndex();
917 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RematIdx));
924 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
925 const TargetRegisterClass* RC,
927 MachineInstr* Barrier,
928 MachineBasicBlock* MBB,
930 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
931 MachineBasicBlock::iterator Pt = MBB->begin();
933 // Go top down if RefsInMBB is empty.
934 if (RefsInMBB.empty())
937 MachineBasicBlock::iterator FoldPt = Barrier;
938 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
939 !RefsInMBB.count(FoldPt))
942 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
946 SmallVector<unsigned, 1> Ops;
947 Ops.push_back(OpIdx);
949 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
952 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
953 if (I != IntervalSSMap.end()) {
956 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
959 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
963 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
964 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
967 IntervalSSMap[vreg] = SS;
968 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
969 if (CurrSLI->hasAtLeastOneValue())
970 CurrSValNo = CurrSLI->getValNumInfo(0);
972 CurrSValNo = CurrSLI->getNextValue(LiveIndex(), 0, false,
973 LSs->getVNInfoAllocator());
979 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
980 const TargetRegisterClass* RC,
981 MachineInstr* Barrier,
982 MachineBasicBlock* MBB,
984 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
985 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
988 // Go top down if RefsInMBB is empty.
989 if (RefsInMBB.empty())
992 // Can't fold a restore between a call stack setup and teardown.
993 MachineBasicBlock::iterator FoldPt = Barrier;
995 // Advance from barrier to call frame teardown.
996 while (FoldPt != MBB->getFirstTerminator() &&
997 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
998 if (RefsInMBB.count(FoldPt))
1004 if (FoldPt == MBB->getFirstTerminator())
1009 // Now find the restore point.
1010 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
1011 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
1012 while (FoldPt != MBB->getFirstTerminator() &&
1013 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1014 if (RefsInMBB.count(FoldPt))
1020 if (FoldPt == MBB->getFirstTerminator())
1027 if (FoldPt == MBB->getFirstTerminator())
1030 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1034 SmallVector<unsigned, 1> Ops;
1035 Ops.push_back(OpIdx);
1037 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1040 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1044 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1045 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1052 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1053 /// so it would not cross the barrier that's being processed. Shrink wrap
1054 /// (minimize) the live interval to the last uses.
1055 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1056 DEBUG(errs() << "Pre-alloc splitting " << LI->reg << " for " << *Barrier
1061 // Find live range where current interval cross the barrier.
1062 LiveInterval::iterator LR =
1063 CurrLI->FindLiveRangeContaining(BarrierIdx.getUseIndex());
1064 VNInfo *ValNo = LR->valno;
1066 assert(!ValNo->isUnused() && "Val# is defined by a dead def?");
1068 MachineInstr *DefMI = ValNo->isDefAccurate()
1069 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1071 // If this would create a new join point, do not split.
1072 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent())) {
1073 DEBUG(errs() << "FAILED (would create a new join point).\n");
1077 // Find all references in the barrier mbb.
1078 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1079 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1080 E = MRI->reg_end(); I != E; ++I) {
1081 MachineInstr *RefMI = &*I;
1082 if (RefMI->getParent() == BarrierMBB)
1083 RefsInMBB.insert(RefMI);
1086 // Find a point to restore the value after the barrier.
1087 LiveIndex RestoreIndex;
1088 MachineBasicBlock::iterator RestorePt =
1089 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1090 if (RestorePt == BarrierMBB->end()) {
1091 DEBUG(errs() << "FAILED (could not find a suitable restore point).\n");
1095 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1096 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1097 RestoreIndex, RefsInMBB)) {
1098 DEBUG(errs() << "success (remat).\n");
1102 // Add a spill either before the barrier or after the definition.
1103 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1104 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1105 LiveIndex SpillIndex;
1106 MachineInstr *SpillMI = NULL;
1108 if (!ValNo->isDefAccurate()) {
1109 // If we don't know where the def is we must split just before the barrier.
1110 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1111 BarrierMBB, SS, RefsInMBB))) {
1112 SpillIndex = LIs->getInstructionIndex(SpillMI);
1114 MachineBasicBlock::iterator SpillPt =
1115 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1116 if (SpillPt == BarrierMBB->begin()) {
1117 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1118 return false; // No gap to insert spill.
1122 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1123 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1124 SpillMI = prior(SpillPt);
1125 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1127 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1128 RestoreIndex, SpillIndex, SS)) {
1129 // If it's already split, just restore the value. There is no need to spill
1132 DEBUG(errs() << "FAILED (def is dead).\n");
1133 return false; // Def is dead. Do nothing.
1136 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1137 BarrierMBB, SS, RefsInMBB))) {
1138 SpillIndex = LIs->getInstructionIndex(SpillMI);
1140 // Check if it's possible to insert a spill after the def MI.
1141 MachineBasicBlock::iterator SpillPt;
1142 if (DefMBB == BarrierMBB) {
1143 // Add spill after the def and the last use before the barrier.
1144 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1145 RefsInMBB, SpillIndex);
1146 if (SpillPt == DefMBB->begin()) {
1147 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1148 return false; // No gap to insert spill.
1151 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1152 if (SpillPt == DefMBB->end()) {
1153 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1154 return false; // No gap to insert spill.
1158 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1159 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg, false, SS, RC);
1160 SpillMI = prior(SpillPt);
1161 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1165 // Remember def instruction index to spill index mapping.
1166 if (DefMI && SpillMI)
1167 Def2SpillMap[ValNo->def] = SpillIndex;
1170 bool FoldedRestore = false;
1171 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1172 BarrierMBB, SS, RefsInMBB)) {
1174 RestoreIndex = LIs->getInstructionIndex(RestorePt);
1175 FoldedRestore = true;
1177 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1178 MachineInstr *LoadMI = prior(RestorePt);
1179 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1182 // Update spill stack slot live interval.
1183 UpdateSpillSlotInterval(ValNo, SpillIndex.getUseIndex().getNextSlot(),
1184 RestoreIndex.getDefIndex());
1186 ReconstructLiveInterval(CurrLI);
1188 if (!FoldedRestore) {
1189 LiveIndex RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1190 RestoreIdx = RestoreIdx.getDefIndex();
1191 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RestoreIdx));
1195 DEBUG(errs() << "success.\n");
1199 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1200 /// barrier that's being processed.
1202 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1203 SmallPtrSet<LiveInterval*, 8>& Split) {
1204 // First find all the virtual registers whose live intervals are intercepted
1205 // by the current barrier.
1206 SmallVector<LiveInterval*, 8> Intervals;
1207 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1208 // FIXME: If it's not safe to move any instruction that defines the barrier
1209 // register class, then it means there are some special dependencies which
1210 // codegen is not modelling. Ignore these barriers for now.
1211 if (!TII->isSafeToMoveRegClassDefs(*RC))
1213 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1214 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1215 unsigned Reg = VRs[i];
1216 if (!LIs->hasInterval(Reg))
1218 LiveInterval *LI = &LIs->getInterval(Reg);
1219 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1220 // Virtual register live interval is intercepted by the barrier. We
1221 // should split and shrink wrap its interval if possible.
1222 Intervals.push_back(LI);
1226 // Process the affected live intervals.
1227 bool Change = false;
1228 while (!Intervals.empty()) {
1229 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1231 LiveInterval *LI = Intervals.back();
1232 Intervals.pop_back();
1233 bool result = SplitRegLiveInterval(LI);
1234 if (result) Split.insert(LI);
1241 unsigned PreAllocSplitting::getNumberOfNonSpills(
1242 SmallPtrSet<MachineInstr*, 4>& MIs,
1243 unsigned Reg, int FrameIndex,
1244 bool& FeedsTwoAddr) {
1245 unsigned NonSpills = 0;
1246 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1248 int StoreFrameIndex;
1249 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1250 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1253 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1254 if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1255 FeedsTwoAddr = true;
1261 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1262 /// split, and see if any of the spills are unnecessary. If so, remove them.
1263 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1264 bool changed = false;
1266 // Walk over all of the live intervals that were touched by the splitter,
1267 // and see if we can do any DCE and/or folding.
1268 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1269 LE = split.end(); LI != LE; ++LI) {
1270 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1272 // First, collect all the uses of the vreg, and sort them by their
1273 // reaching definition (VNInfo).
1274 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1275 UE = MRI->use_end(); UI != UE; ++UI) {
1276 LiveIndex index = LIs->getInstructionIndex(&*UI);
1277 index = index.getUseIndex();
1279 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1280 VNUseCount[LR->valno].insert(&*UI);
1283 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1284 // and/or fold them away.
1285 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1286 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1288 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1291 VNInfo* CurrVN = *VI;
1293 // We don't currently try to handle definitions with PHI kills, because
1294 // it would involve processing more than one VNInfo at once.
1295 if (CurrVN->hasPHIKill()) continue;
1297 // We also don't try to handle the results of PHI joins, since there's
1298 // no defining instruction to analyze.
1299 if (!CurrVN->isDefAccurate() || CurrVN->isUnused()) continue;
1301 // We're only interested in eliminating cruft introduced by the splitter,
1302 // is of the form load-use or load-use-store. First, check that the
1303 // definition is a load, and remember what stack slot we loaded it from.
1304 MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1306 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1308 // If the definition has no uses at all, just DCE it.
1309 if (VNUseCount[CurrVN].size() == 0) {
1310 LIs->RemoveMachineInstrFromMaps(DefMI);
1311 (*LI)->removeValNo(CurrVN);
1312 DefMI->eraseFromParent();
1313 VNUseCount.erase(CurrVN);
1319 // Second, get the number of non-store uses of the definition, as well as
1320 // a flag indicating whether it feeds into a later two-address definition.
1321 bool FeedsTwoAddr = false;
1322 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1323 (*LI)->reg, FrameIndex,
1326 // If there's one non-store use and it doesn't feed a two-addr, then
1327 // this is a load-use-store case that we can try to fold.
1328 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1329 // Start by finding the non-store use MachineInstr.
1330 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1331 int StoreFrameIndex;
1332 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1333 while (UI != VNUseCount[CurrVN].end() &&
1334 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1336 if (UI != VNUseCount[CurrVN].end())
1337 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1339 if (UI == VNUseCount[CurrVN].end()) continue;
1341 MachineInstr* use = *UI;
1343 // Attempt to fold it away!
1344 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1345 if (OpIdx == -1) continue;
1346 SmallVector<unsigned, 1> Ops;
1347 Ops.push_back(OpIdx);
1348 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1350 MachineInstr* NewMI =
1351 TII->foldMemoryOperand(*use->getParent()->getParent(),
1352 use, Ops, FrameIndex);
1354 if (!NewMI) continue;
1356 // Update relevant analyses.
1357 LIs->RemoveMachineInstrFromMaps(DefMI);
1358 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1359 (*LI)->removeValNo(CurrVN);
1361 DefMI->eraseFromParent();
1362 MachineBasicBlock* MBB = use->getParent();
1363 NewMI = MBB->insert(MBB->erase(use), NewMI);
1364 VNUseCount[CurrVN].erase(use);
1366 // Remove deleted instructions. Note that we need to remove them from
1367 // the VNInfo->use map as well, just to be safe.
1368 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1369 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1371 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1372 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1374 if (VNI->first != CurrVN)
1375 VNI->second.erase(*II);
1376 LIs->RemoveMachineInstrFromMaps(*II);
1377 (*II)->eraseFromParent();
1380 VNUseCount.erase(CurrVN);
1382 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1383 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1384 if (VI->second.erase(use))
1385 VI->second.insert(NewMI);
1392 // If there's more than one non-store instruction, we can't profitably
1393 // fold it, so bail.
1394 if (NonSpillCount) continue;
1396 // Otherwise, this is a load-store case, so DCE them.
1397 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1398 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1400 LIs->RemoveMachineInstrFromMaps(*UI);
1401 (*UI)->eraseFromParent();
1404 VNUseCount.erase(CurrVN);
1406 LIs->RemoveMachineInstrFromMaps(DefMI);
1407 (*LI)->removeValNo(CurrVN);
1408 DefMI->eraseFromParent();
1417 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1418 MachineBasicBlock* DefMBB,
1419 MachineBasicBlock* BarrierMBB) {
1420 if (DefMBB == BarrierMBB)
1423 if (LR->valno->hasPHIKill())
1426 LiveIndex MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1427 if (LR->end < MBBEnd)
1430 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1431 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1434 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1435 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1436 typedef std::pair<MachineBasicBlock*,
1437 MachineBasicBlock::succ_iterator> ItPair;
1438 SmallVector<ItPair, 4> Stack;
1439 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1441 while (!Stack.empty()) {
1442 ItPair P = Stack.back();
1445 MachineBasicBlock* PredMBB = P.first;
1446 MachineBasicBlock::succ_iterator S = P.second;
1448 if (S == PredMBB->succ_end())
1450 else if (Visited.count(*S)) {
1451 Stack.push_back(std::make_pair(PredMBB, ++S));
1454 Stack.push_back(std::make_pair(PredMBB, S+1));
1456 MachineBasicBlock* MBB = *S;
1457 Visited.insert(MBB);
1459 if (MBB == BarrierMBB)
1462 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1463 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1464 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1466 if (MDTN == DefMDTN)
1468 else if (MDTN == BarrierMDTN)
1470 MDTN = MDTN->getIDom();
1473 MBBEnd = LIs->getMBBEndIdx(MBB);
1474 if (LR->end > MBBEnd)
1475 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1482 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1484 TM = &MF.getTarget();
1485 TRI = TM->getRegisterInfo();
1486 TII = TM->getInstrInfo();
1487 MFI = MF.getFrameInfo();
1488 MRI = &MF.getRegInfo();
1489 LIs = &getAnalysis<LiveIntervals>();
1490 LSs = &getAnalysis<LiveStacks>();
1491 VRM = &getAnalysis<VirtRegMap>();
1493 bool MadeChange = false;
1495 // Make sure blocks are numbered in order.
1496 MF.RenumberBlocks();
1498 MachineBasicBlock *Entry = MF.begin();
1499 SmallPtrSet<MachineBasicBlock*,16> Visited;
1501 SmallPtrSet<LiveInterval*, 8> Split;
1503 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1504 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1507 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1508 E = BarrierMBB->end(); I != E; ++I) {
1510 const TargetRegisterClass **BarrierRCs =
1511 Barrier->getDesc().getRegClassBarriers();
1514 BarrierIdx = LIs->getInstructionIndex(Barrier);
1515 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1519 MadeChange |= removeDeadSpills(Split);