15 #define DEBUG_TYPE "regalloc"
49 STATISTIC(NumGlobalSplits,
"Number of split global live ranges");
50 STATISTIC(NumLocalSplits,
"Number of split local live ranges");
51 STATISTIC(NumEvicted,
"Number of interferences evicted");
55 cl::desc(
"Spill mode for splitting live ranges"),
84 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
100 enum LiveRangeStage {
124 static const char *
const StageName[];
129 LiveRangeStage Stage;
134 RegInfo() : Stage(RS_New), Cascade(0) {}
139 LiveRangeStage getStage(
const LiveInterval &VirtReg)
const {
140 return ExtraRegInfo[VirtReg.
reg].Stage;
143 void setStage(
const LiveInterval &VirtReg, LiveRangeStage Stage) {
144 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
145 ExtraRegInfo[VirtReg.
reg].Stage = Stage;
148 template<
typename Iterator>
149 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
150 ExtraRegInfo.resize(
MRI->getNumVirtRegs());
151 for (;Begin != End; ++Begin) {
152 unsigned Reg = *Begin;
153 if (ExtraRegInfo[Reg].Stage == RS_New)
154 ExtraRegInfo[
Reg].Stage = NewStage;
159 struct EvictionCost {
160 unsigned BrokenHints;
163 EvictionCost(
unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
165 bool isMax()
const {
return BrokenHints == ~0u; }
167 bool operator<(
const EvictionCost &O)
const {
168 if (BrokenHints != O.BrokenHints)
169 return BrokenHints < O.BrokenHints;
170 return MaxWeight < O.MaxWeight;
185 struct GlobalSplitCandidate {
202 Intf.setPhysReg(Cache, Reg);
204 ActiveBlocks.clear();
210 for (
int i = LiveBundles.find_first(); i >= 0;
211 i = LiveBundles.find_next(i))
212 if (B[i] == NoCand) {
235 virtual const char* getPassName()
const {
236 return "Greedy Register Allocator";
241 virtual void releaseMemory();
242 virtual Spiller &spiller() {
return *SpillerInstance; }
254 bool LRE_CanEraseVirtReg(
unsigned);
255 void LRE_WillShrinkVirtReg(
unsigned);
256 void LRE_DidCloneVirtReg(
unsigned,
unsigned);
261 void growRegion(GlobalSplitCandidate &Cand);
263 bool calcCompactRegion(GlobalSplitCandidate&);
266 unsigned canReassign(
LiveInterval &VirtReg,
unsigned PhysReg);
268 bool canEvictInterference(
LiveInterval&,
unsigned,
bool, EvictionCost&);
292 const char *
const RAGreedy::StageName[] = {
308 return new RAGreedy();
351 MachineFunctionPass::getAnalysisUsage(AU);
359 bool RAGreedy::LRE_CanEraseVirtReg(
unsigned VirtReg) {
360 if (VRM->hasPhys(VirtReg)) {
361 Matrix->unassign(LIS->getInterval(VirtReg));
369 void RAGreedy::LRE_WillShrinkVirtReg(
unsigned VirtReg) {
370 if (!VRM->hasPhys(VirtReg))
379 void RAGreedy::LRE_DidCloneVirtReg(
unsigned New,
unsigned Old) {
381 if (!ExtraRegInfo.inBounds(Old))
388 ExtraRegInfo[Old].Stage = RS_Assign;
389 ExtraRegInfo.grow(New);
390 ExtraRegInfo[New] = ExtraRegInfo[Old];
393 void RAGreedy::releaseMemory() {
394 SpillerInstance.reset(0);
395 ExtraRegInfo.clear();
402 const unsigned Size = LI->
getSize();
403 const unsigned Reg = LI->
reg;
404 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
405 "Can only enqueue virtual registers");
408 ExtraRegInfo.grow(Reg);
409 if (ExtraRegInfo[Reg].Stage == RS_New)
410 ExtraRegInfo[
Reg].Stage = RS_Assign;
412 if (ExtraRegInfo[Reg].Stage == RS_Split) {
417 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->
empty() &&
418 LIS->intervalIsInOneMBB(*LI)) {
428 Prio = (1u << 29) + Size;
434 if (VRM->hasKnownPreference(Reg))
439 Queue.push(std::make_pair(Prio, ~Reg));
445 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
461 while ((PhysReg = Order.
next()))
462 if (!
Matrix->checkInterference(VirtReg, PhysReg))
464 if (!PhysReg || Order.
isHint())
471 if (
unsigned Hint =
MRI->getSimpleHint(VirtReg.
reg))
474 EvictionCost MaxCost(1);
475 if (canEvictInterference(VirtReg, Hint,
true, MaxCost)) {
476 evictInterference(VirtReg, Hint, NewVRegs);
482 unsigned Cost = TRI->getCostPerUse(PhysReg);
490 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
491 return CheapReg ? CheapReg : PhysReg;
499 unsigned RAGreedy::canReassign(
LiveInterval &VirtReg,
unsigned PrevReg) {
502 while ((PhysReg = Order.
next())) {
503 if (PhysReg == PrevReg)
507 for (; Units.isValid(); ++Units) {
510 if (subQ.checkInterference())
514 if (!Units.isValid())
518 DEBUG(
dbgs() <<
"can reassign: " << VirtReg <<
" from "
539 bool CanSplit = getStage(B) < RS_Spill;
543 if (CanSplit && IsHint && !BreaksHint)
558 bool RAGreedy::canEvictInterference(
LiveInterval &VirtReg,
unsigned PhysReg,
559 bool IsHint, EvictionCost &MaxCost) {
561 if (
Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
564 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
573 unsigned Cascade = ExtraRegInfo[VirtReg.
reg].Cascade;
575 Cascade = NextCascade;
587 assert(TargetRegisterInfo::isVirtualRegister(Intf->
reg) &&
588 "Only expecting virtual register interference from query");
590 if (getStage(*Intf) == RS_Done)
603 unsigned IntfCascade = ExtraRegInfo[Intf->
reg].Cascade;
604 if (Cascade <= IntfCascade) {
609 Cost.BrokenHints += 10;
612 bool BreaksHint = VRM->hasPreferredPhys(Intf->
reg);
614 Cost.BrokenHints += BreaksHint;
615 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->
weight);
617 if (!(Cost < MaxCost))
624 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
625 !canReassign(*Intf, PhysReg)) {
629 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
640 void RAGreedy::evictInterference(
LiveInterval &VirtReg,
unsigned PhysReg,
645 unsigned Cascade = ExtraRegInfo[VirtReg.
reg].Cascade;
647 Cascade = ExtraRegInfo[VirtReg.
reg].Cascade = NextCascade++;
650 <<
" interference: Cascade " << Cascade <<
'\n');
658 Intfs.
append(IVR.begin(), IVR.end());
662 for (
unsigned i = 0, e = Intfs.
size(); i != e; ++i) {
665 if (!VRM->hasPhys(Intf->
reg))
668 assert((ExtraRegInfo[Intf->
reg].Cascade < Cascade ||
670 "Cannot decrease cascade number, illegal eviction");
671 ExtraRegInfo[Intf->
reg].Cascade = Cascade;
684 unsigned CostPerUseLimit) {
688 EvictionCost BestCost(~0u);
689 unsigned BestPhys = 0;
694 if (CostPerUseLimit < ~0u) {
695 BestCost.BrokenHints = 0;
696 BestCost.MaxWeight = VirtReg.
weight;
700 unsigned MinCost = RegClassInfo.getMinCost(RC);
701 if (MinCost >= CostPerUseLimit) {
703 <<
", no cheaper registers to be found.\n");
709 if (TRI->getCostPerUse(Order.
getOrder().
back()) >= CostPerUseLimit) {
710 OrderLimit = RegClassInfo.getLastCostChange(RC);
711 DEBUG(
dbgs() <<
"Only trying the first " << OrderLimit <<
" regs.\n");
716 while (
unsigned PhysReg = Order.
nextWithDups(OrderLimit)) {
717 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
721 if (CostPerUseLimit == 1)
722 if (
unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
723 if (!
MRI->isPhysRegUsed(CSR)) {
729 if (!canEvictInterference(VirtReg, PhysReg,
false, BestCost))
743 evictInterference(VirtReg, BestPhys, NewVRegs);
762 SplitConstraints.resize(UseBlocks.
size());
764 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
770 BC.
Entry = BI.
LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
771 BC.
Exit = BI.
LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
782 if (Intf.
first() <= Indexes->getMBBStartIdx(BC.
Number))
783 BC.
Entry = SpillPlacement::MustSpill, ++Ins;
785 BC.
Entry = SpillPlacement::PrefSpill, ++Ins;
792 if (Intf.
last() >= SA->getLastSplitPoint(BC.
Number))
793 BC.
Exit = SpillPlacement::MustSpill, ++Ins;
795 BC.
Exit = SpillPlacement::PrefSpill, ++Ins;
802 StaticCost += SpillPlacer->getBlockFrequency(BC.
Number);
808 SpillPlacer->addConstraints(SplitConstraints);
809 return SpillPlacer->scanActiveBundles();
817 const unsigned GroupSize = 8;
819 unsigned TBS[GroupSize];
820 unsigned B = 0,
T = 0;
822 for (
unsigned i = 0; i != Blocks.
size(); ++i) {
823 unsigned Number = Blocks[i];
827 assert(
T < GroupSize &&
"Array overflow");
829 if (++
T == GroupSize) {
836 assert(B < GroupSize &&
"Array overflow");
840 if (Intf.
first() <= Indexes->getMBBStartIdx(Number))
841 BCS[B].Entry = SpillPlacement::MustSpill;
843 BCS[B].
Entry = SpillPlacement::PrefSpill;
846 if (Intf.
last() >= SA->getLastSplitPoint(Number))
847 BCS[B].Exit = SpillPlacement::MustSpill;
849 BCS[B].
Exit = SpillPlacement::PrefSpill;
851 if (++B == GroupSize) {
853 SpillPlacer->addConstraints(Array);
859 SpillPlacer->addConstraints(Array);
863 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
867 unsigned AddedTo = 0;
869 unsigned Visited = 0;
875 for (
int i = 0, e = NewBundles.
size(); i != e; ++i) {
876 unsigned Bundle = NewBundles[i];
882 if (!Todo.
test(Block))
893 if (ActiveBlocks.
size() == AddedTo)
900 addThroughConstraints(Cand.Intf, NewBlocks);
904 SpillPlacer->addPrefSpill(NewBlocks,
true);
905 AddedTo = ActiveBlocks.
size();
908 SpillPlacer->iterate();
920 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
922 if (!SA->getNumThroughBlocks())
926 Cand.reset(IntfCache, 0);
928 DEBUG(
dbgs() <<
"Compact region bundles");
932 SpillPlacer->prepare(Cand.LiveBundles);
936 if (!addSplitConstraints(Cand.Intf, Cost)) {
942 SpillPlacer->finish();
944 if (!Cand.LiveBundles.any()) {
950 for (
int i = Cand.LiveBundles.find_first(); i>=0;
951 i = Cand.LiveBundles.find_next(i))
952 dbgs() <<
" EB#" << i;
963 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
967 Cost += SpillPlacer->getBlockFrequency(Number);
971 Cost += SpillPlacer->getBlockFrequency(Number);
980 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
982 const BitVector &LiveBundles = Cand.LiveBundles;
984 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
987 bool RegIn = LiveBundles[Bundles->getBundle(BC.
Number, 0)];
988 bool RegOut = LiveBundles[Bundles->getBundle(BC.
Number, 1)];
992 Ins += RegIn != (BC.
Entry == SpillPlacement::PrefReg);
994 Ins += RegOut != (BC.
Exit == SpillPlacement::PrefReg);
996 GlobalCost += SpillPlacer->getBlockFrequency(BC.
Number);
999 for (
unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1000 unsigned Number = Cand.ActiveBlocks[i];
1001 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1002 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1003 if (!RegIn && !RegOut)
1005 if (RegIn && RegOut) {
1007 Cand.Intf.moveToBlock(Number);
1008 if (Cand.Intf.hasInterference()) {
1009 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1010 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1015 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1036 const unsigned NumGlobalIntvs = LREdit.
size();
1037 DEBUG(
dbgs() <<
"splitAroundRegion with " << NumGlobalIntvs <<
" globals.\n");
1038 assert(NumGlobalIntvs &&
"No global intervals configured");
1043 unsigned Reg = SA->getParent().reg;
1044 bool SingleInstrs = RegClassInfo.isProperSubClass(
MRI->
getRegClass(Reg));
1048 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1051 unsigned IntvIn = 0, IntvOut = 0;
1054 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1055 if (CandIn != NoCand) {
1056 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1057 IntvIn = Cand.IntvIdx;
1058 Cand.Intf.moveToBlock(Number);
1059 IntfIn = Cand.Intf.first();
1063 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1064 if (CandOut != NoCand) {
1065 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1066 IntvOut = Cand.IntvIdx;
1067 Cand.Intf.moveToBlock(Number);
1068 IntfOut = Cand.Intf.last();
1073 if (!IntvIn && !IntvOut) {
1075 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1076 SE->splitSingleBlock(BI);
1080 if (IntvIn && IntvOut)
1081 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1083 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1085 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1091 BitVector Todo = SA->getThroughBlocks();
1092 for (
unsigned c = 0; c != UsedCands.
size(); ++c) {
1094 for (
unsigned i = 0, e = Blocks.
size(); i != e; ++i) {
1095 unsigned Number = Blocks[i];
1096 if (!Todo.
test(Number))
1100 unsigned IntvIn = 0, IntvOut = 0;
1103 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1104 if (CandIn != NoCand) {
1105 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1106 IntvIn = Cand.IntvIdx;
1107 Cand.Intf.moveToBlock(Number);
1108 IntfIn = Cand.Intf.first();
1111 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1112 if (CandOut != NoCand) {
1113 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1114 IntvOut = Cand.IntvIdx;
1115 Cand.Intf.moveToBlock(Number);
1116 IntfOut = Cand.Intf.last();
1118 if (!IntvIn && !IntvOut)
1120 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1127 SE->finish(&IntvMap);
1128 DebugVars->splitRegister(Reg, LREdit.
regs(), *LIS);
1130 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
1131 unsigned OrigBlocks = SA->getNumLiveBlocks();
1138 for (
unsigned i = 0, e = LREdit.
size(); i != e; ++i) {
1142 if (getStage(Reg) != RS_New)
1147 if (IntvMap[i] == 0) {
1148 setStage(Reg, RS_Spill);
1154 if (IntvMap[i] < NumGlobalIntvs) {
1155 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1156 DEBUG(
dbgs() <<
"Main interval covers the same " << OrigBlocks
1157 <<
" blocks as original.\n");
1159 setStage(Reg, RS_Split2);
1169 MF->verify(
this,
"After splitting live range around region");
1174 unsigned NumCands = 0;
1175 unsigned BestCand = NoCand;
1180 bool HasCompact = calcCompactRegion(GlobalCand.front());
1184 BestCost = BlockFrequency::getMaxFrequency();
1188 BestCost = calcSpillCost();
1189 DEBUG(
dbgs() <<
"Cost of isolating all blocks = " << BestCost <<
'\n');
1193 while (
unsigned PhysReg = Order.
next()) {
1196 if (NumCands == IntfCache.getMaxCursors()) {
1197 unsigned WorstCount = ~0u;
1199 for (
unsigned i = 0; i != NumCands; ++i) {
1200 if (i == BestCand || !GlobalCand[i].PhysReg)
1202 unsigned Count = GlobalCand[i].LiveBundles.count();
1203 if (Count < WorstCount)
1204 Worst = i, WorstCount = Count;
1207 GlobalCand[Worst] = GlobalCand[NumCands];
1208 if (BestCand == NumCands)
1212 if (GlobalCand.size() <= NumCands)
1213 GlobalCand.resize(NumCands+1);
1214 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1215 Cand.reset(IntfCache, PhysReg);
1217 SpillPlacer->prepare(Cand.LiveBundles);
1219 if (!addSplitConstraints(Cand.Intf, Cost)) {
1224 if (Cost >= BestCost) {
1226 if (BestCand == NoCand)
1227 dbgs() <<
" worse than no bundles\n";
1229 dbgs() <<
" worse than "
1230 <<
PrintReg(GlobalCand[BestCand].PhysReg, TRI) <<
'\n';
1236 SpillPlacer->finish();
1239 if (!Cand.LiveBundles.any()) {
1244 Cost += calcGlobalSplitCost(Cand);
1246 dbgs() <<
", total = " << Cost <<
" with bundles";
1247 for (
int i = Cand.LiveBundles.find_first(); i>=0;
1248 i = Cand.LiveBundles.find_next(i))
1249 dbgs() <<
" EB#" << i;
1252 if (Cost < BestCost) {
1253 BestCand = NumCands;
1260 if (!HasCompact && BestCand == NoCand)
1264 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this);
1268 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1271 if (BestCand != NoCand) {
1272 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1273 if (
unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1275 Cand.IntvIdx = SE->openIntv();
1277 << B <<
" bundles, intv " << Cand.IntvIdx <<
".\n");
1284 GlobalSplitCandidate &Cand = GlobalCand.front();
1285 assert(!Cand.PhysReg &&
"Compact region has no physreg");
1286 if (
unsigned B = Cand.getBundles(BundleCand, 0)) {
1288 Cand.IntvIdx = SE->openIntv();
1289 DEBUG(
dbgs() <<
"Split for compact region in " << B <<
" bundles, intv "
1290 << Cand.IntvIdx <<
".\n");
1295 splitAroundRegion(LREdit, UsedCands);
1309 assert(&SA->getParent() == &VirtReg &&
"Live range wasn't analyzed");
1310 unsigned Reg = VirtReg.
reg;
1311 bool SingleInstrs = RegClassInfo.isProperSubClass(
MRI->
getRegClass(Reg));
1312 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this);
1315 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1317 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1318 SE->splitSingleBlock(BI);
1326 SE->finish(&IntvMap);
1329 DebugVars->splitRegister(Reg, LREdit.
regs(), *LIS);
1331 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
1335 for (
unsigned i = 0, e = LREdit.
size(); i != e; ++i) {
1337 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1338 setStage(LI, RS_Spill);
1342 MF->
verify(
this,
"After splitting live range around basic blocks");
1367 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this);
1368 SE->reset(LREdit, SplitEditor::SM_Size);
1371 if (Uses.
size() <= 1)
1374 DEBUG(
dbgs() <<
"Split around " << Uses.
size() <<
" individual instrs.\n");
1377 for (
unsigned i = 0; i != Uses.
size(); ++i) {
1378 if (
const MachineInstr *
MI = Indexes->getInstructionFromIndex(Uses[i]))
1379 if (
MI->isFullCopy()) {
1380 DEBUG(
dbgs() <<
" skip:\t" << Uses[i] <<
'\t' << *
MI);
1384 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1385 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1386 SE->useIntv(SegStart, SegStop);
1389 if (LREdit.
empty()) {
1390 DEBUG(
dbgs() <<
"All uses were copies.\n");
1395 SE->finish(&IntvMap);
1396 DebugVars->splitRegister(VirtReg.
reg, LREdit.
regs(), *LIS);
1397 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
1400 setStage(LREdit.
begin(), LREdit.
end(), RS_Spill);
1415 void RAGreedy::calcGapWeights(
unsigned PhysReg,
1417 assert(SA->getUseBlocks().size() == 1 &&
"Not a local interval");
1420 const unsigned NumGaps = Uses.
size()-1;
1424 BI.LiveIn ? BI.FirstInstr.
getBaseIndex() : BI.FirstInstr;
1428 GapWeight.
assign(NumGaps, 0.0f);
1432 if (!
Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1433 .checkInterference())
1444 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1445 for (
unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1447 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1448 if (++Gap == NumGaps)
1454 const float weight = IntI.value()->weight;
1455 for (; Gap != NumGaps; ++Gap) {
1456 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1457 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1467 const LiveRange &LR = LIS->getRegUnit(*Units);
1472 for (
unsigned Gap = 0; I != E && I->start < StopIdx; ++
I) {
1473 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1474 if (++Gap == NumGaps)
1479 for (; Gap != NumGaps; ++Gap) {
1481 if (Uses[Gap+1].getBaseIndex() >= I->end)
1495 assert(SA->getUseBlocks().size() == 1 &&
"Not a local interval");
1506 if (Uses.
size() <= 2)
1508 const unsigned NumGaps = Uses.
size()-1;
1511 dbgs() <<
"tryLocalSplit: ";
1512 for (
unsigned i = 0, e = Uses.
size(); i != e; ++i)
1513 dbgs() <<
' ' << Uses[i];
1520 if (
Matrix->checkRegMaskInterference(VirtReg)) {
1525 unsigned ri = std::lower_bound(RMS.
begin(), RMS.
end(),
1527 unsigned re = RMS.
size();
1528 for (
unsigned i = 0; i != NumGaps && ri != re; ++i) {
1530 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1531 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1535 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1537 DEBUG(
dbgs() <<
' ' << RMS[ri] <<
':' << Uses[i] <<
'-' << Uses[i+1]);
1538 RegMaskGaps.push_back(i);
1541 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1565 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1568 unsigned BestBefore = NumGaps;
1569 unsigned BestAfter = 0;
1572 const float blockFreq =
1573 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1574 (1.0f / BlockFrequency::getEntryFrequency());
1578 while (
unsigned PhysReg = Order.
next()) {
1581 calcGapWeights(PhysReg, GapWeight);
1584 if (
Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1585 for (
unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1592 unsigned SplitBefore = 0, SplitAfter = 1;
1596 float MaxGap = GapWeight[0];
1600 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1601 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1604 << Uses[SplitBefore] <<
'-' << Uses[SplitAfter]
1605 <<
" i=" << MaxGap);
1608 if (!LiveBefore && !LiveAfter) {
1616 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1619 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1628 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1629 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1635 float Diff = EstWeight - MaxGap;
1636 if (Diff > BestDiff) {
1639 BestBefore = SplitBefore;
1640 BestAfter = SplitAfter;
1647 if (++SplitBefore < SplitAfter) {
1650 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1651 MaxGap = GapWeight[SplitBefore];
1652 for (
unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1653 MaxGap = std::max(MaxGap, GapWeight[i]);
1661 if (SplitAfter >= NumGaps) {
1667 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1672 if (BestBefore == NumGaps)
1675 DEBUG(
dbgs() <<
"Best local split range: " << Uses[BestBefore]
1676 <<
'-' << Uses[BestAfter] <<
", " << BestDiff
1677 <<
", " << (BestAfter - BestBefore + 1) <<
" instrs\n");
1679 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this);
1683 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1684 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1685 SE->useIntv(SegStart, SegStop);
1687 SE->finish(&IntvMap);
1688 DebugVars->splitRegister(VirtReg.
reg, LREdit.
regs(), *LIS);
1693 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1694 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1695 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1696 if (NewGaps >= NumGaps) {
1697 DEBUG(
dbgs() <<
"Tagging non-progress ranges: ");
1698 assert(!ProgressRequired &&
"Didn't make progress when it was required.");
1699 for (
unsigned i = 0, e = IntvMap.
size(); i != e; ++i)
1700 if (IntvMap[i] == 1) {
1701 setStage(LIS->getInterval(LREdit.
get(i)), RS_Split2);
1721 if (getStage(VirtReg) >= RS_Spill)
1725 if (LIS->intervalIsInOneMBB(VirtReg)) {
1727 SA->analyze(&VirtReg);
1728 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1729 if (PhysReg || !NewVRegs.
empty())
1731 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1736 SA->analyze(&VirtReg);
1742 if (SA->didRepairRange()) {
1744 Matrix->invalidateVirtRegs();
1745 if (
unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1752 if (getStage(VirtReg) < RS_Split2) {
1753 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1754 if (PhysReg || !NewVRegs.
empty())
1759 return tryBlockSplit(VirtReg, Order, NewVRegs);
1767 unsigned RAGreedy::selectOrSplit(
LiveInterval &VirtReg,
1771 if (
unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1774 LiveRangeStage Stage = getStage(VirtReg);
1776 <<
" Cascade " << ExtraRegInfo[VirtReg.
reg].Cascade <<
'\n');
1781 if (Stage != RS_Split)
1782 if (
unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1785 assert(NewVRegs.
empty() &&
"Cannot append to existing NewVRegs");
1790 if (Stage < RS_Split) {
1791 setStage(VirtReg, RS_Split);
1792 DEBUG(
dbgs() <<
"wait for second round\n");
1803 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1804 if (PhysReg || !NewVRegs.
empty())
1809 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this);
1810 spiller().spill(LRE);
1811 setStage(NewVRegs.
begin(), NewVRegs.
end(), RS_Done);
1814 MF->verify(
this,
"After spilling");
1822 DEBUG(
dbgs() <<
"********** GREEDY REGISTER ALLOCATION **********\n"
1823 <<
"********** Function: " << mf.
getName() <<
'\n');
1827 MF->
verify(
this,
"Before greedy register allocator");
1830 getAnalysis<LiveIntervals>(),
1831 getAnalysis<LiveRegMatrix>());
1832 Indexes = &getAnalysis<SlotIndexes>();
1833 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1834 DomTree = &getAnalysis<MachineDominatorTree>();
1836 Loops = &getAnalysis<MachineLoopInfo>();
1837 Bundles = &getAnalysis<EdgeBundles>();
1838 SpillPlacer = &getAnalysis<SpillPlacement>();
1839 DebugVars = &getAnalysis<LiveDebugVariables>();
1846 SE.reset(
new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
1847 ExtraRegInfo.clear();
1848 ExtraRegInfo.resize(
MRI->getNumVirtRegs());
1850 IntfCache.init(MF,
Matrix->getLiveUnions(), Indexes, LIS, TRI);
1851 GlobalCand.resize(32);
bool seenAllInterferences() const
void push_back(const T &Elt)
AnalysisUsage & addPreserved()
static PassRegistry * getPassRegistry()
void rewind()
Start over from the beginning.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
SlotIndex getBoundaryIndex() const
int getInstrDistance(SlotIndex other) const
SlotIndex getBaseIndex() const
void verify(Pass *p=NULL, const char *Banner=NULL) const
const T & front() const
front - Get the first element.
void initializeLiveDebugVariablesPass(PassRegistry &)
ArrayRef< MCPhysReg > getOrder() const
Get the allocation order without reordered hints.
bool isSpillable() const
isSpillable - Can this interval be spilled?
SlotIndex FirstDef
First non-phi valno->def, or SlotIndex().
ValuesClass< DataType > END_WITH_NULL values(const char *Arg, DataType Val, const char *Desc,...)
void operator<(const Optional< T > &X, const Optional< U > &Y)
Poison comparison between two Optional objects. Clients needs to explicitly compare the underlying va...
void initializeMachineLoopInfoPass(PassRegistry &)
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
static float normalizeSpillWeight(float UseDefFreq, unsigned Size)
Normalize the spill weight of a live interval.
Callback methods for LiveRangeEdit owners.
void initializeRegisterCoalescerPass(PassRegistry &)
LoopInfoBase< BlockT, LoopT > * LI
unsigned nextWithDups(unsigned Limit)
AnalysisUsage & addRequired()
const char * getName() const
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void assign(unsigned NumElts, const T &Elt)
enum LLVM_ENUM_INT_TYPE(uint32_t)
ID
LLVM Calling Convention Representation.
BorderConstraint Exit
Constraint on block exit.
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
BlockConstraint - Entry and exit constraints for a basic block.
size_t size() const
size - Get the array size.
SlotIndex LastInstr
Last instr accessing current reg.
unsigned get(unsigned idx) const
void initializeMachineDominatorTreePass(PassRegistry &)
initializer< Ty > init(const Ty &Val)
void initializeSlotIndexesPass(PassRegistry &)
* if(!EatIfPresent(lltok::kw_thread_local)) return false
void initializeLiveStacksPass(PassRegistry &)
Cursor - The primary query interface for the block interference cache.
const MCRegisterClass & getRegClass(unsigned i) const
Returns the register class associated with the enumeration value. See class MCOperandInfo.
void initializeLiveIntervalsPass(PassRegistry &)
unsigned Number
Basic block number (from MBB::getNumber()).
void resize(typename StorageT::size_type s)
static cl::opt< SplitEditor::ComplementSpillMode > SplitSpillMode("split-spill-mode", cl::Hidden, cl::desc("Spill mode for splitting live ranges"), cl::values(clEnumValN(SplitEditor::SM_Partition,"default","Default"), clEnumValN(SplitEditor::SM_Size,"size","Optimize for size"), clEnumValN(SplitEditor::SM_Speed,"speed","Optimize for speed"), clEnumValEnd), cl::init(SplitEditor::SM_Partition))
void verify() const
Walk the range and assert if any invariants fail to hold.
void append(in_iter in_start, in_iter in_end)
BorderConstraint Entry
Constraint on block entry.
const T & back() const
back - Get the last element.
iterator find(SlotIndex Pos)
STATISTIC(NumGlobalSplits,"Number of split global live ranges")
SlotIndex FirstInstr
First instr accessing current reg.
bool test(unsigned Idx) const
bool hasInterference()
hasInterference - Return true if the current block has any interference.
void initializeSpillPlacementPass(PassRegistry &)
void initializeMachineSchedulerPass(PassRegistry &)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
static RegisterRegAlloc greedyRegAlloc("greedy","greedy register allocator", createGreedyRegisterAllocator)
LiveSegments::iterator SegmentIter
bool LiveOut
Current reg is live out.
void moveToBlock(unsigned MBBNum)
moveTo - Move cursor to basic block MBBNum.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
void initializeVirtRegMapPass(PassRegistry &)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
ArrayRef< unsigned > regs() const
void initializeLiveRegMatrixPass(PassRegistry &)
FunctionPass * createGreedyRegisterAllocator()
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=UINT_MAX)
SlotIndex getRegSlot(bool EC=false) const
bool isHint() const
Return true if the last register returned from next() was a preferred register.
void initializeEdgeBundlesPass(PassRegistry &)
const MCRegisterInfo & MRI
StringRef getName() const
bool TimePassesIsEnabled
This is the storage for the -time-passes option.
bool LiveIn
Current reg is live in.
SlotIndex - An opaque wrapper around machine indexes.