1 //===-- PreAllocSplitting.cpp - Pre-allocation Interval Spltting Pass. ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the machine instruction level pre-register allocation
11 // live interval splitting pass. It finds live interval barriers, i.e.
12 // instructions which will kill all physical registers in certain register
13 // classes, and split all live intervals which cross the barrier.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "pre-alloc-split"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
39 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
41 STATISTIC(NumSplits, "Number of intervals split");
42 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
43 STATISTIC(NumFolds, "Number of intervals split with spill folding");
44 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
45 STATISTIC(NumDeadSpills, "Number of dead spills removed");
48 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
49 MachineFunction *CurrMF;
50 const TargetMachine *TM;
51 const TargetInstrInfo *TII;
52 MachineFrameInfo *MFI;
53 MachineRegisterInfo *MRI;
57 // Barrier - Current barrier being processed.
58 MachineInstr *Barrier;
60 // BarrierMBB - Basic block where the barrier resides in.
61 MachineBasicBlock *BarrierMBB;
63 // Barrier - Current barrier index.
66 // CurrLI - Current live interval being split.
69 // CurrSLI - Current stack slot live interval.
70 LiveInterval *CurrSLI;
72 // CurrSValNo - Current val# for the stack slot live interval.
75 // IntervalSSMap - A map from live interval to spill slots.
76 DenseMap<unsigned, int> IntervalSSMap;
78 // Def2SpillMap - A map from a def instruction index to spill index.
79 DenseMap<unsigned, unsigned> Def2SpillMap;
83 PreAllocSplitting() : MachineFunctionPass(&ID) {}
85 virtual bool runOnMachineFunction(MachineFunction &MF);
87 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.addRequired<LiveIntervals>();
89 AU.addPreserved<LiveIntervals>();
90 AU.addRequired<LiveStacks>();
91 AU.addPreserved<LiveStacks>();
92 AU.addPreserved<RegisterCoalescer>();
94 AU.addPreservedID(StrongPHIEliminationID);
96 AU.addPreservedID(PHIEliminationID);
97 AU.addRequired<MachineDominatorTree>();
98 AU.addRequired<MachineLoopInfo>();
99 AU.addPreserved<MachineDominatorTree>();
100 AU.addPreserved<MachineLoopInfo>();
101 MachineFunctionPass::getAnalysisUsage(AU);
104 virtual void releaseMemory() {
105 IntervalSSMap.clear();
106 Def2SpillMap.clear();
109 virtual const char *getPassName() const {
110 return "Pre-Register Allocaton Live Interval Splitting";
113 /// print - Implement the dump method.
114 virtual void print(std::ostream &O, const Module* M = 0) const {
118 void print(std::ostream *O, const Module* M = 0) const {
123 MachineBasicBlock::iterator
124 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
127 MachineBasicBlock::iterator
128 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
129 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
131 MachineBasicBlock::iterator
132 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
133 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
135 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
137 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
138 unsigned&, int&) const;
140 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
142 bool SplitRegLiveInterval(LiveInterval*);
144 bool SplitRegLiveIntervals(const TargetRegisterClass **,
145 SmallPtrSet<LiveInterval*, 8>&);
147 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
148 MachineBasicBlock* BarrierMBB);
149 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
151 MachineBasicBlock::iterator RestorePt,
153 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
154 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
156 MachineInstr* Barrier,
157 MachineBasicBlock* MBB,
159 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
160 void RenumberValno(VNInfo* VN);
161 void ReconstructLiveInterval(LiveInterval* LI);
162 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
163 unsigned getNumberOfSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
164 unsigned Reg, int FrameIndex);
165 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator use,
166 MachineBasicBlock* MBB,
168 SmallPtrSet<MachineInstr*, 4>& Visited,
169 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
170 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
171 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
172 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
173 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
174 bool toplevel, bool intrablock);
176 } // end anonymous namespace
178 char PreAllocSplitting::ID = 0;
180 static RegisterPass<PreAllocSplitting>
181 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
183 const PassInfo *const llvm::PreAllocSplittingID = &X;
186 /// findNextEmptySlot - Find a gap after the given machine instruction in the
187 /// instruction index map. If there isn't one, return end().
188 MachineBasicBlock::iterator
189 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
190 unsigned &SpotIndex) {
191 MachineBasicBlock::iterator MII = MI;
192 if (++MII != MBB->end()) {
193 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
202 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
203 /// for spilling the current live interval. The index must be before any
204 /// defs and uses of the live interval register in the mbb. Return begin() if
206 MachineBasicBlock::iterator
207 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
209 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
210 unsigned &SpillIndex) {
211 MachineBasicBlock::iterator Pt = MBB->begin();
213 // Go top down if RefsInMBB is empty.
214 if (RefsInMBB.empty() && !DefMI) {
215 MachineBasicBlock::iterator MII = MBB->begin();
216 MachineBasicBlock::iterator EndPt = MI;
219 unsigned Index = LIs->getInstructionIndex(MII);
220 unsigned Gap = LIs->findGapBeforeInstr(Index);
226 } while (MII != EndPt);
228 MachineBasicBlock::iterator MII = MI;
229 MachineBasicBlock::iterator EndPt = DefMI
230 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
231 while (MII != EndPt && !RefsInMBB.count(MII)) {
232 unsigned Index = LIs->getInstructionIndex(MII);
233 if (LIs->hasGapBeforeInstr(Index)) {
235 SpillIndex = LIs->findGapBeforeInstr(Index, true);
244 /// findRestorePoint - Find a gap in the instruction index map that's suitable
245 /// for restoring the current live interval value. The index must be before any
246 /// uses of the live interval register in the mbb. Return end() if none is
248 MachineBasicBlock::iterator
249 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
251 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
252 unsigned &RestoreIndex) {
253 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
254 // begin index accordingly.
255 MachineBasicBlock::iterator Pt = MBB->end();
256 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
258 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
259 // the last index in the live range.
260 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
261 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
262 MachineBasicBlock::iterator EndPt = MI;
265 unsigned Index = LIs->getInstructionIndex(MII);
266 unsigned Gap = LIs->findGapBeforeInstr(Index);
273 } while (MII != EndPt);
275 MachineBasicBlock::iterator MII = MI;
277 // FIXME: Limit the number of instructions to examine to reduce
279 while (MII != MBB->end()) {
280 unsigned Index = LIs->getInstructionIndex(MII);
283 unsigned Gap = LIs->findGapBeforeInstr(Index);
288 if (RefsInMBB.count(MII))
297 /// CreateSpillStackSlot - Create a stack slot for the live interval being
298 /// split. If the live interval was previously split, just reuse the same
300 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
301 const TargetRegisterClass *RC) {
303 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
304 if (I != IntervalSSMap.end()) {
307 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
308 IntervalSSMap[Reg] = SS;
311 // Create live interval for stack slot.
312 CurrSLI = &LSs->getOrCreateInterval(SS);
313 if (CurrSLI->hasAtLeastOneValue())
314 CurrSValNo = CurrSLI->getValNumInfo(0);
316 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
320 /// IsAvailableInStack - Return true if register is available in a split stack
321 /// slot at the specified index.
323 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
324 unsigned Reg, unsigned DefIndex,
325 unsigned RestoreIndex, unsigned &SpillIndex,
330 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
331 if (I == IntervalSSMap.end())
333 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
334 if (II == Def2SpillMap.end())
337 // If last spill of def is in the same mbb as barrier mbb (where restore will
338 // be), make sure it's not below the intended restore index.
339 // FIXME: Undo the previous spill?
340 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
341 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
345 SpillIndex = II->second;
349 /// UpdateSpillSlotInterval - Given the specified val# of the register live
350 /// interval being split, and the spill and restore indicies, update the live
351 /// interval of the spill stack slot.
353 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
354 unsigned RestoreIndex) {
355 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
356 "Expect restore in the barrier mbb");
358 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
359 if (MBB == BarrierMBB) {
360 // Intra-block spill + restore. We are done.
361 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
362 CurrSLI->addRange(SLR);
366 SmallPtrSet<MachineBasicBlock*, 4> Processed;
367 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
368 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
369 CurrSLI->addRange(SLR);
370 Processed.insert(MBB);
372 // Start from the spill mbb, figure out the extend of the spill slot's
374 SmallVector<MachineBasicBlock*, 4> WorkList;
375 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
376 if (LR->end > EndIdx)
377 // If live range extend beyond end of mbb, add successors to work list.
378 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
379 SE = MBB->succ_end(); SI != SE; ++SI)
380 WorkList.push_back(*SI);
382 while (!WorkList.empty()) {
383 MachineBasicBlock *MBB = WorkList.back();
385 if (Processed.count(MBB))
387 unsigned Idx = LIs->getMBBStartIdx(MBB);
388 LR = CurrLI->getLiveRangeContaining(Idx);
389 if (LR && LR->valno == ValNo) {
390 EndIdx = LIs->getMBBEndIdx(MBB);
391 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
392 // Spill slot live interval stops at the restore.
393 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
394 CurrSLI->addRange(SLR);
395 } else if (LR->end > EndIdx) {
396 // Live range extends beyond end of mbb, process successors.
397 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
398 CurrSLI->addRange(SLR);
399 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
400 SE = MBB->succ_end(); SI != SE; ++SI)
401 WorkList.push_back(*SI);
403 LiveRange SLR(Idx, LR->end, CurrSValNo);
404 CurrSLI->addRange(SLR);
406 Processed.insert(MBB);
411 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
412 /// construction algorithm to compute the ranges and valnos for an interval.
413 VNInfo* PreAllocSplitting::PerformPHIConstruction(
414 MachineBasicBlock::iterator use,
415 MachineBasicBlock* MBB,
417 SmallPtrSet<MachineInstr*, 4>& Visited,
418 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
419 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
420 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
421 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
422 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
423 bool toplevel, bool intrablock) {
424 // Return memoized result if it's available.
425 if (toplevel && Visited.count(use) && NewVNs.count(use))
427 else if (!toplevel && intrablock && NewVNs.count(use))
429 else if (!intrablock && LiveOut.count(MBB))
432 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
434 // Check if our block contains any uses or defs.
435 bool ContainsDefs = Defs.count(MBB);
436 bool ContainsUses = Uses.count(MBB);
440 // Enumerate the cases of use/def contaning blocks.
441 if (!ContainsDefs && !ContainsUses) {
443 // NOTE: Because this is the fallback case from other cases, we do NOT
444 // assume that we are not intrablock here.
445 if (Phis.count(MBB)) return Phis[MBB];
447 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
449 if (MBB->pred_size() == 1) {
450 Phis[MBB] = ret = PerformPHIConstruction((*MBB->pred_begin())->end(),
451 *(MBB->pred_begin()), LI, Visited,
452 Defs, Uses, NewVNs, LiveOut, Phis,
454 unsigned EndIndex = 0;
456 EndIndex = LIs->getInstructionIndex(use);
457 EndIndex = LiveIntervals::getUseIndex(EndIndex);
459 EndIndex = LIs->getMBBEndIdx(MBB);
461 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
463 LI->addKill(ret, EndIndex);
465 Phis[MBB] = ret = LI->getNextValue(~0U, /*FIXME*/ 0,
466 LIs->getVNInfoAllocator());
467 if (!intrablock) LiveOut[MBB] = ret;
469 // If there are no uses or defs between our starting point and the
470 // beginning of the block, then recursive perform phi construction
471 // on our predecessors.
472 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
473 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
474 PE = MBB->pred_end(); PI != PE; ++PI) {
475 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
476 Visited, Defs, Uses, NewVNs,
477 LiveOut, Phis, false, false);
479 IncomingVNs[*PI] = Incoming;
482 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
483 // VNInfo to represent the joined value.
484 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
485 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
486 I->second->hasPHIKill = true;
487 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
488 LI->addKill(I->second, KillIndex);
491 unsigned EndIndex = 0;
493 EndIndex = LIs->getInstructionIndex(use);
494 EndIndex = LiveIntervals::getUseIndex(EndIndex);
496 EndIndex = LIs->getMBBEndIdx(MBB);
497 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
499 LI->addKill(ret, EndIndex);
501 } else if (ContainsDefs && !ContainsUses) {
502 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
504 // Search for the def in this block. If we don't find it before the
505 // instruction we care about, go to the fallback case. Note that that
506 // should never happen: this cannot be intrablock, so use should
507 // always be an end() iterator.
508 assert(use == MBB->end() && "No use marked in intrablock");
510 MachineBasicBlock::iterator walker = use;
512 while (walker != MBB->begin())
513 if (BlockDefs.count(walker)) {
518 // Once we've found it, extend its VNInfo to our instruction.
519 unsigned DefIndex = LIs->getInstructionIndex(walker);
520 DefIndex = LiveIntervals::getDefIndex(DefIndex);
521 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
523 ret = NewVNs[walker];
524 LI->addRange(LiveRange(DefIndex, EndIndex+1, ret));
525 } else if (!ContainsDefs && ContainsUses) {
526 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
528 // Search for the use in this block that precedes the instruction we care
529 // about, going to the fallback case if we don't find it.
531 if (use == MBB->begin())
534 MachineBasicBlock::iterator walker = use;
537 while (walker != MBB->begin())
538 if (BlockUses.count(walker)) {
544 // Must check begin() too.
546 if (BlockUses.count(walker))
552 unsigned UseIndex = LIs->getInstructionIndex(walker);
553 UseIndex = LiveIntervals::getUseIndex(UseIndex);
554 unsigned EndIndex = 0;
556 EndIndex = LIs->getInstructionIndex(use);
557 EndIndex = LiveIntervals::getUseIndex(EndIndex);
559 EndIndex = LIs->getMBBEndIdx(MBB);
561 // Now, recursively phi construct the VNInfo for the use we found,
562 // and then extend it to include the instruction we care about
563 ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
564 NewVNs, LiveOut, Phis, false, true);
566 // FIXME: Need to set kills properly for inter-block stuff.
567 if (LI->isKill(ret, UseIndex)) LI->removeKill(ret, UseIndex);
569 LI->addKill(ret, EndIndex);
571 LI->addRange(LiveRange(UseIndex, EndIndex+1, ret));
572 } else if (ContainsDefs && ContainsUses){
573 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
574 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
576 // This case is basically a merging of the two preceding case, with the
577 // special note that checking for defs must take precedence over checking
578 // for uses, because of two-address instructions.
580 if (use == MBB->begin())
583 MachineBasicBlock::iterator walker = use;
585 bool foundDef = false;
586 bool foundUse = false;
587 while (walker != MBB->begin())
588 if (BlockDefs.count(walker)) {
591 } else if (BlockUses.count(walker)) {
597 // Must check begin() too.
598 if (!foundDef && !foundUse) {
599 if (BlockDefs.count(walker))
601 else if (BlockUses.count(walker))
607 unsigned StartIndex = LIs->getInstructionIndex(walker);
608 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
609 LiveIntervals::getUseIndex(StartIndex);
610 unsigned EndIndex = 0;
612 EndIndex = LIs->getInstructionIndex(use);
613 EndIndex = LiveIntervals::getUseIndex(EndIndex);
615 EndIndex = LIs->getMBBEndIdx(MBB);
618 ret = NewVNs[walker];
620 ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
621 NewVNs, LiveOut, Phis, false, true);
623 if (foundUse && LI->isKill(ret, StartIndex))
624 LI->removeKill(ret, StartIndex);
626 LI->addKill(ret, EndIndex);
629 LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
632 // Memoize results so we don't have to recompute them.
633 if (!intrablock) LiveOut[MBB] = ret;
635 if (!NewVNs.count(use))
643 /// ReconstructLiveInterval - Recompute a live interval from scratch.
644 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
645 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
647 // Clear the old ranges and valnos;
650 // Cache the uses and defs of the register
651 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
654 // Keep track of the new VNs we're creating.
655 DenseMap<MachineInstr*, VNInfo*> NewVNs;
656 SmallPtrSet<VNInfo*, 2> PhiVNs;
658 // Cache defs, and create a new VNInfo for each def.
659 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
660 DE = MRI->def_end(); DI != DE; ++DI) {
661 Defs[(*DI).getParent()].insert(&*DI);
663 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
664 DefIdx = LiveIntervals::getDefIndex(DefIdx);
666 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
668 // If the def is a move, set the copy field.
669 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
670 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
671 if (DstReg == LI->reg)
674 NewVNs[&*DI] = NewVN;
677 // Cache uses as a separate pass from actually processing them.
678 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
679 UE = MRI->use_end(); UI != UE; ++UI)
680 Uses[(*UI).getParent()].insert(&*UI);
682 // Now, actually process every use and use a phi construction algorithm
683 // to walk from it to its reaching definitions, building VNInfos along
685 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
686 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
687 SmallPtrSet<MachineInstr*, 4> Visited;
688 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
689 UE = MRI->use_end(); UI != UE; ++UI) {
690 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
691 Uses, NewVNs, LiveOut, Phis, true, true);
694 // Add ranges for dead defs
695 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
696 DE = MRI->def_end(); DI != DE; ++DI) {
697 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
698 DefIdx = LiveIntervals::getDefIndex(DefIdx);
700 if (LI->liveAt(DefIdx)) continue;
702 VNInfo* DeadVN = NewVNs[&*DI];
703 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
704 LI->addKill(DeadVN, DefIdx);
708 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
709 /// be allocated to a different register. This function creates a new vreg,
710 /// copies the valno and its live ranges over to the new vreg's interval,
711 /// removes them from the old interval, and rewrites all uses and defs of
712 /// the original reg to the new vreg within those ranges.
713 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
714 SmallVector<VNInfo*, 4> Stack;
715 SmallVector<VNInfo*, 4> VNsToCopy;
718 // Walk through and copy the valno we care about, and any other valnos
719 // that are two-address redefinitions of the one we care about. These
720 // will need to be rewritten as well. We also check for safety of the
721 // renumbering here, by making sure that none of the valno involved has
723 while (!Stack.empty()) {
724 VNInfo* OldVN = Stack.back();
727 // Bail out if we ever encounter a valno that has a PHI kill. We can't
729 if (OldVN->hasPHIKill) return;
731 VNsToCopy.push_back(OldVN);
733 // Locate two-address redefinitions
734 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
735 KE = OldVN->kills.end(); KI != KE; ++KI) {
736 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
738 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
739 if (DefIdx == ~0U) continue;
740 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
742 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
743 Stack.push_back(NextVN);
748 // Create the new vreg
749 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
751 // Create the new live interval
752 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
754 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
755 VNsToCopy.end(); OI != OE; ++OI) {
758 // Copy the valno over
759 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
760 LIs->getVNInfoAllocator());
761 NewLI.copyValNumInfo(NewVN, OldVN);
762 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
764 // Remove the valno from the old interval
765 CurrLI->removeValNo(OldVN);
768 // Rewrite defs and uses. This is done in two stages to avoid invalidating
770 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
772 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
773 E = MRI->reg_end(); I != E; ++I) {
774 MachineOperand& MO = I.getOperand();
775 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
777 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
778 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
779 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
782 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
783 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
784 MachineInstr* Inst = I->first;
785 unsigned OpIdx = I->second;
786 MachineOperand& MO = Inst->getOperand(OpIdx);
793 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
795 MachineBasicBlock::iterator RestorePt,
797 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
798 MachineBasicBlock& MBB = *RestorePt->getParent();
800 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
801 unsigned KillIdx = 0;
802 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
803 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
805 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
807 if (KillPt == DefMI->getParent()->end())
810 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
811 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
813 if (KillPt->getParent() == BarrierMBB) {
814 VNInfo* After = UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
815 LIs->getDefIndex(RestoreIdx));
817 RenumberValno(After);
824 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIdx);
831 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
832 const TargetRegisterClass* RC,
834 MachineInstr* Barrier,
835 MachineBasicBlock* MBB,
837 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
838 MachineBasicBlock::iterator Pt = MBB->begin();
840 // Go top down if RefsInMBB is empty.
841 if (RefsInMBB.empty())
844 MachineBasicBlock::iterator FoldPt = Barrier;
845 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
846 !RefsInMBB.count(FoldPt))
849 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
853 SmallVector<unsigned, 1> Ops;
854 Ops.push_back(OpIdx);
856 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
859 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
860 if (I != IntervalSSMap.end()) {
863 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
867 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
871 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
872 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
875 IntervalSSMap[vreg] = SS;
876 CurrSLI = &LSs->getOrCreateInterval(SS);
877 if (CurrSLI->hasAtLeastOneValue())
878 CurrSValNo = CurrSLI->getValNumInfo(0);
880 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
886 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
887 /// so it would not cross the barrier that's being processed. Shrink wrap
888 /// (minimize) the live interval to the last uses.
889 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
892 // Find live range where current interval cross the barrier.
893 LiveInterval::iterator LR =
894 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
895 VNInfo *ValNo = LR->valno;
897 if (ValNo->def == ~1U) {
898 // Defined by a dead def? How can this be?
899 assert(0 && "Val# is defined by a dead def?");
903 MachineInstr *DefMI = (ValNo->def != ~0U)
904 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
906 // If this would create a new join point, do not split.
907 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
910 // Find all references in the barrier mbb.
911 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
912 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
913 E = MRI->reg_end(); I != E; ++I) {
914 MachineInstr *RefMI = &*I;
915 if (RefMI->getParent() == BarrierMBB)
916 RefsInMBB.insert(RefMI);
919 // Find a point to restore the value after the barrier.
920 unsigned RestoreIndex = 0;
921 MachineBasicBlock::iterator RestorePt =
922 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
923 if (RestorePt == BarrierMBB->end())
926 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
927 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
928 RestoreIndex, RefsInMBB))
931 // Add a spill either before the barrier or after the definition.
932 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
933 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
934 unsigned SpillIndex = 0;
935 MachineInstr *SpillMI = NULL;
937 if (ValNo->def == ~0U) {
938 // If it's defined by a phi, we must split just before the barrier.
939 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
940 BarrierMBB, SS, RefsInMBB))) {
941 SpillIndex = LIs->getInstructionIndex(SpillMI);
943 MachineBasicBlock::iterator SpillPt =
944 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
945 if (SpillPt == BarrierMBB->begin())
946 return false; // No gap to insert spill.
949 SS = CreateSpillStackSlot(CurrLI->reg, RC);
950 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
951 SpillMI = prior(SpillPt);
952 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
954 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
955 RestoreIndex, SpillIndex, SS)) {
956 // If it's already split, just restore the value. There is no need to spill
959 return false; // Def is dead. Do nothing.
961 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
962 BarrierMBB, SS, RefsInMBB))) {
963 SpillIndex = LIs->getInstructionIndex(SpillMI);
965 // Check if it's possible to insert a spill after the def MI.
966 MachineBasicBlock::iterator SpillPt;
967 if (DefMBB == BarrierMBB) {
968 // Add spill after the def and the last use before the barrier.
969 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
970 RefsInMBB, SpillIndex);
971 if (SpillPt == DefMBB->begin())
972 return false; // No gap to insert spill.
974 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
975 if (SpillPt == DefMBB->end())
976 return false; // No gap to insert spill.
978 // Add spill. The store instruction kills the register if def is before
979 // the barrier in the barrier block.
980 SS = CreateSpillStackSlot(CurrLI->reg, RC);
981 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
982 DefMBB == BarrierMBB, SS, RC);
983 SpillMI = prior(SpillPt);
984 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
988 // Remember def instruction index to spill index mapping.
989 if (DefMI && SpillMI)
990 Def2SpillMap[ValNo->def] = SpillIndex;
993 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
994 MachineInstr *LoadMI = prior(RestorePt);
995 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
997 // If live interval is spilled in the same block as the barrier, just
998 // create a hole in the interval.
1000 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
1001 // Update spill stack slot live interval.
1002 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1003 LIs->getDefIndex(RestoreIndex));
1005 VNInfo* After = UpdateRegisterInterval(ValNo,
1006 LIs->getUseIndex(SpillIndex)+1,
1007 LIs->getDefIndex(RestoreIndex));
1008 RenumberValno(After);
1014 // Update spill stack slot live interval.
1015 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1016 LIs->getDefIndex(RestoreIndex));
1018 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIndex);
1024 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1025 /// barrier that's being processed.
1027 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1028 SmallPtrSet<LiveInterval*, 8>& Split) {
1029 // First find all the virtual registers whose live intervals are intercepted
1030 // by the current barrier.
1031 SmallVector<LiveInterval*, 8> Intervals;
1032 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1033 if (TII->IgnoreRegisterClassBarriers(*RC))
1035 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1036 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1037 unsigned Reg = VRs[i];
1038 if (!LIs->hasInterval(Reg))
1040 LiveInterval *LI = &LIs->getInterval(Reg);
1041 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1042 // Virtual register live interval is intercepted by the barrier. We
1043 // should split and shrink wrap its interval if possible.
1044 Intervals.push_back(LI);
1048 // Process the affected live intervals.
1049 bool Change = false;
1050 while (!Intervals.empty()) {
1051 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1053 else if (NumSplits == 4)
1055 LiveInterval *LI = Intervals.back();
1056 Intervals.pop_back();
1057 bool result = SplitRegLiveInterval(LI);
1058 if (result) Split.insert(LI);
1065 unsigned PreAllocSplitting::getNumberOfSpills(
1066 SmallPtrSet<MachineInstr*, 4>& MIs,
1067 unsigned Reg, int FrameIndex) {
1068 unsigned Spills = 0;
1069 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1071 int StoreFrameIndex;
1072 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1073 if (StoreVReg == Reg && StoreFrameIndex == FrameIndex)
1080 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1081 /// split, and see if any of the spills are unnecessary. If so, remove them.
1082 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1083 bool changed = false;
1085 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1086 LE = split.end(); LI != LE; ++LI) {
1087 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1089 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1090 UE = MRI->use_end(); UI != UE; ++UI) {
1091 unsigned index = LIs->getInstructionIndex(&*UI);
1092 index = LiveIntervals::getUseIndex(index);
1094 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1095 VNUseCount[LR->valno].insert(&*UI);
1098 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1099 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1100 VNInfo* CurrVN = *VI;
1101 if (CurrVN->hasPHIKill) continue;
1103 unsigned DefIdx = CurrVN->def;
1104 if (DefIdx == ~0U || DefIdx == ~1U) continue;
1106 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1108 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1110 if (VNUseCount[CurrVN].size() == 0) {
1111 LIs->RemoveMachineInstrFromMaps(DefMI);
1112 (*LI)->removeValNo(CurrVN);
1113 DefMI->eraseFromParent();
1119 unsigned SpillCount = getNumberOfSpills(VNUseCount[CurrVN],
1120 (*LI)->reg, FrameIndex);
1121 if (SpillCount != VNUseCount[CurrVN].size()) continue;
1123 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1124 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1126 LIs->RemoveMachineInstrFromMaps(*UI);
1127 (*UI)->eraseFromParent();
1130 LIs->RemoveMachineInstrFromMaps(DefMI);
1131 (*LI)->removeValNo(CurrVN);
1132 DefMI->eraseFromParent();
1141 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1142 MachineBasicBlock* DefMBB,
1143 MachineBasicBlock* BarrierMBB) {
1144 if (DefMBB == BarrierMBB)
1147 if (LR->valno->hasPHIKill)
1150 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1151 if (LR->end < MBBEnd)
1154 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1155 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1158 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1159 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1160 typedef std::pair<MachineBasicBlock*,
1161 MachineBasicBlock::succ_iterator> ItPair;
1162 SmallVector<ItPair, 4> Stack;
1163 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1165 while (!Stack.empty()) {
1166 ItPair P = Stack.back();
1169 MachineBasicBlock* PredMBB = P.first;
1170 MachineBasicBlock::succ_iterator S = P.second;
1172 if (S == PredMBB->succ_end())
1174 else if (Visited.count(*S)) {
1175 Stack.push_back(std::make_pair(PredMBB, ++S));
1178 Stack.push_back(std::make_pair(PredMBB, S+1));
1180 MachineBasicBlock* MBB = *S;
1181 Visited.insert(MBB);
1183 if (MBB == BarrierMBB)
1186 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1187 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1188 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1190 if (MDTN == DefMDTN)
1192 else if (MDTN == BarrierMDTN)
1194 MDTN = MDTN->getIDom();
1197 MBBEnd = LIs->getMBBEndIdx(MBB);
1198 if (LR->end > MBBEnd)
1199 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1206 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1208 TM = &MF.getTarget();
1209 TII = TM->getInstrInfo();
1210 MFI = MF.getFrameInfo();
1211 MRI = &MF.getRegInfo();
1212 LIs = &getAnalysis<LiveIntervals>();
1213 LSs = &getAnalysis<LiveStacks>();
1215 bool MadeChange = false;
1217 // Make sure blocks are numbered in order.
1218 MF.RenumberBlocks();
1220 MachineBasicBlock *Entry = MF.begin();
1221 SmallPtrSet<MachineBasicBlock*,16> Visited;
1223 SmallPtrSet<LiveInterval*, 8> Split;
1225 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1226 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1229 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1230 E = BarrierMBB->end(); I != E; ++I) {
1232 const TargetRegisterClass **BarrierRCs =
1233 Barrier->getDesc().getRegClassBarriers();
1236 BarrierIdx = LIs->getInstructionIndex(Barrier);
1237 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1241 MadeChange |= removeDeadSpills(Split);