82 #define DEBUG_TYPE "regalloc"
84 STATISTIC(NumGlobalSplits,
"Number of split global live ranges");
85 STATISTIC(NumLocalSplits,
"Number of split local live ranges");
86 STATISTIC(NumEvicted,
"Number of interferences evicted");
90 cl::desc(
"Spill mode for splitting live ranges"),
98 cl::desc(
"Last chance recoloring max depth"),
103 cl::desc(
"Last chance recoloring maximum number of considered"
104 " interference at a time"),
109 cl::desc(
"Exhaustive Search for registers bypassing the depth "
110 "and interference cutoffs of last chance recoloring"));
114 cl::desc(
"Local reassignment can yield better allocation decisions, but "
115 "may be compile time intensive"),
120 cl::desc(
"Instead of spilling a variable right away, defer the actual "
121 "code insertion to the end of the allocation. That way the "
122 "allocator might still find a suitable coloring for this "
123 "variable because of other evicted variables."),
129 cl::desc(
"Cost for first time use of callee-saved register."),
141 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
165 std::unique_ptr<Spiller> SpillerInstance;
167 unsigned NextCascade;
182 enum LiveRangeStage {
227 static const char *
const StageName[];
232 LiveRangeStage Stage = RS_New;
235 unsigned Cascade = 0;
242 LiveRangeStage getStage(
const LiveInterval &VirtReg)
const {
243 return ExtraRegInfo[VirtReg.
reg].Stage;
246 void setStage(
const LiveInterval &VirtReg, LiveRangeStage Stage) {
247 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
248 ExtraRegInfo[VirtReg.
reg].Stage = Stage;
251 template<
typename Iterator>
252 void setStage(Iterator Begin, Iterator
End, LiveRangeStage NewStage) {
253 ExtraRegInfo.resize(
MRI->getNumVirtRegs());
254 for (;Begin !=
End; ++Begin) {
255 unsigned Reg = *Begin;
256 if (ExtraRegInfo[Reg].Stage == RS_New)
257 ExtraRegInfo[
Reg].Stage = NewStage;
262 struct EvictionCost {
263 unsigned BrokenHints = 0;
266 EvictionCost() =
default;
268 bool isMax()
const {
return BrokenHints == ~0u; }
270 void setMax() { BrokenHints = ~0u; }
272 void setBrokenHints(
unsigned NHints) { BrokenHints = NHints; }
274 bool operator<(
const EvictionCost &O)
const {
275 return std::tie(BrokenHints, MaxWeight) <
276 std::tie(O.BrokenHints, O.MaxWeight);
281 std::unique_ptr<SplitAnalysis> SA;
282 std::unique_ptr<SplitEditor> SE;
291 struct GlobalSplitCandidate {
308 Intf.setPhysReg(Cache, Reg);
310 ActiveBlocks.clear();
316 for (
unsigned i : LiveBundles.set_bits())
330 enum :
unsigned {
NoCand = ~0u };
341 bool EnableLocalReassign;
350 StringRef getPassName()
const override {
return "Greedy Register Allocator"; }
354 void releaseMemory()
override;
355 Spiller &spiller()
override {
return *SpillerInstance; }
373 SmallVirtRegSet &,
unsigned = 0);
375 bool LRE_CanEraseVirtReg(
unsigned)
override;
376 void LRE_WillShrinkVirtReg(
unsigned)
override;
377 void LRE_DidCloneVirtReg(
unsigned,
unsigned)
override;
384 void growRegion(GlobalSplitCandidate &Cand);
386 bool calcCompactRegion(GlobalSplitCandidate&);
389 unsigned canReassign(
LiveInterval &VirtReg,
unsigned PhysReg);
391 bool canEvictInterference(
LiveInterval&,
unsigned,
bool, EvictionCost&);
394 bool mayRecolorAllInterferences(
unsigned PhysReg,
LiveInterval &VirtReg,
395 SmallLISet &RecoloringCandidates,
396 const SmallVirtRegSet &FixedRegisters);
405 unsigned calculateRegionSplitCost(
LiveInterval &VirtReg,
408 unsigned &NumCands,
bool IgnoreCSR);
410 unsigned doRegionSplit(
LiveInterval &VirtReg,
unsigned BestCand,
416 unsigned PhysReg,
unsigned &CostPerUseLimit,
418 void initializeCSRCost();
429 SmallVirtRegSet &,
unsigned);
431 SmallVirtRegSet &,
unsigned);
433 void tryHintsRecoloring();
446 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
451 void collectHintInfo(
unsigned, HintsInfo &);
453 bool isUnusedCalleeSavedReg(
unsigned PhysReg)
const;
456 void reportNumberOfSplillsReloads(
MachineLoop *
L,
unsigned &Reloads,
457 unsigned &FoldedReloads,
unsigned &Spills,
458 unsigned &FoldedSpills);
461 void reportNumberOfSplillsReloads() {
463 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
464 reportNumberOfSplillsReloads(
L, Reloads, FoldedReloads, Spills,
476 "Greedy Register Allocator",
false,
false)
494 const char *
const RAGreedy::StageName[] = {
510 return new RAGreedy();
541 MachineFunctionPass::getAnalysisUsage(AU);
548 bool RAGreedy::LRE_CanEraseVirtReg(
unsigned VirtReg) {
549 if (VRM->hasPhys(VirtReg)) {
552 aboutToRemoveInterval(LI);
560 void RAGreedy::LRE_WillShrinkVirtReg(
unsigned VirtReg) {
561 if (!VRM->hasPhys(VirtReg))
570 void RAGreedy::LRE_DidCloneVirtReg(
unsigned New,
unsigned Old) {
572 if (!ExtraRegInfo.inBounds(Old))
579 ExtraRegInfo[Old].Stage = RS_Assign;
580 ExtraRegInfo.grow(New);
581 ExtraRegInfo[New] = ExtraRegInfo[Old];
584 void RAGreedy::releaseMemory() {
585 SpillerInstance.reset();
586 ExtraRegInfo.clear();
590 void RAGreedy::enqueue(
LiveInterval *LI) { enqueue(Queue, LI); }
592 void RAGreedy::enqueue(PQueue &CurQueue,
LiveInterval *LI) {
596 const unsigned Reg = LI->
reg;
597 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
598 "Can only enqueue virtual registers");
601 ExtraRegInfo.grow(Reg);
602 if (ExtraRegInfo[Reg].Stage == RS_New)
603 ExtraRegInfo[
Reg].Stage = RS_Assign;
605 if (ExtraRegInfo[Reg].Stage == RS_Split) {
609 }
else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
614 static unsigned MemOp = 0;
619 bool ReverseLocal = TRI->reverseLocalAssignment();
621 bool ForceGlobal = !ReverseLocal &&
622 (Size / SlotIndex::InstrDist) > (2 * RC.
getNumRegs());
624 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->
empty() &&
625 LIS->intervalIsInOneMBB(*LI)) {
635 Prio = Indexes->getZeroIndex().getInstrDistance(LI->
endIndex());
642 Prio = (1u << 29) + Size;
648 if (VRM->hasKnownPreference(Reg))
653 CurQueue.push(std::make_pair(Prio, ~Reg));
656 LiveInterval *RAGreedy::dequeue() {
return dequeue(Queue); }
659 if (CurQueue.empty())
661 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
676 while ((PhysReg = Order.
next()))
677 if (!
Matrix->checkInterference(VirtReg, PhysReg))
679 if (!PhysReg || Order.
isHint())
686 if (
unsigned Hint =
MRI->getSimpleHint(VirtReg.
reg))
689 EvictionCost MaxCost;
690 MaxCost.setBrokenHints(1);
691 if (canEvictInterference(VirtReg, Hint,
true, MaxCost)) {
692 evictInterference(VirtReg, Hint, NewVRegs);
697 SetOfBrokenHints.insert(&VirtReg);
701 unsigned Cost = TRI->getCostPerUse(PhysReg);
709 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
710 return CheapReg ? CheapReg : PhysReg;
717 unsigned RAGreedy::canReassign(
LiveInterval &VirtReg,
unsigned PrevReg) {
720 while ((PhysReg = Order.
next())) {
721 if (PhysReg == PrevReg)
725 for (; Units.isValid(); ++Units) {
728 if (subQ.checkInterference())
732 if (!Units.isValid())
736 DEBUG(
dbgs() <<
"can reassign: " << VirtReg <<
" from "
757 bool CanSplit = getStage(B) < RS_Spill;
761 if (CanSplit && IsHint && !BreaksHint)
780 bool RAGreedy::canEvictInterference(
LiveInterval &VirtReg,
unsigned PhysReg,
781 bool IsHint, EvictionCost &MaxCost) {
783 if (
Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
786 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
795 unsigned Cascade = ExtraRegInfo[VirtReg.
reg].Cascade;
797 Cascade = NextCascade;
809 assert(TargetRegisterInfo::isVirtualRegister(Intf->
reg) &&
810 "Only expecting virtual register interference from query");
812 if (getStage(*Intf) == RS_Done)
822 RegClassInfo.getNumAllocatableRegs(
MRI->getRegClass(VirtReg.
reg)) <
823 RegClassInfo.getNumAllocatableRegs(
MRI->getRegClass(Intf->
reg)));
825 unsigned IntfCascade = ExtraRegInfo[Intf->
reg].Cascade;
826 if (Cascade <= IntfCascade) {
831 Cost.BrokenHints += 10;
834 bool BreaksHint = VRM->hasPreferredPhys(Intf->
reg);
836 Cost.BrokenHints += BreaksHint;
839 if (!(Cost < MaxCost))
844 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
849 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
850 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
862 void RAGreedy::evictInterference(
LiveInterval &VirtReg,
unsigned PhysReg,
867 unsigned Cascade = ExtraRegInfo[VirtReg.
reg].Cascade;
869 Cascade = ExtraRegInfo[VirtReg.
reg].Cascade = NextCascade++;
872 <<
" interference: Cascade " << Cascade <<
'\n');
888 for (
unsigned i = 0, e = Intfs.
size(); i != e; ++i) {
891 if (!VRM->hasPhys(Intf->
reg))
894 assert((ExtraRegInfo[Intf->
reg].Cascade < Cascade ||
896 "Cannot decrease cascade number, illegal eviction");
897 ExtraRegInfo[Intf->
reg].Cascade = Cascade;
905 bool RAGreedy::isUnusedCalleeSavedReg(
unsigned PhysReg)
const {
906 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
910 return !
Matrix->isPhysRegUsed(PhysReg);
920 unsigned CostPerUseLimit) {
925 EvictionCost BestCost;
927 unsigned BestPhys = 0;
932 if (CostPerUseLimit < ~0u) {
933 BestCost.BrokenHints = 0;
934 BestCost.MaxWeight = VirtReg.
weight;
938 unsigned MinCost = RegClassInfo.getMinCost(RC);
939 if (MinCost >= CostPerUseLimit) {
940 DEBUG(
dbgs() << TRI->getRegClassName(RC) <<
" minimum cost = " << MinCost
941 <<
", no cheaper registers to be found.\n");
947 if (TRI->getCostPerUse(Order.
getOrder().
back()) >= CostPerUseLimit) {
948 OrderLimit = RegClassInfo.getLastCostChange(RC);
949 DEBUG(
dbgs() <<
"Only trying the first " << OrderLimit <<
" regs.\n");
954 while (
unsigned PhysReg = Order.
next(OrderLimit)) {
955 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
959 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
961 <<
PrintReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
966 if (!canEvictInterference(VirtReg, PhysReg,
false, BestCost))
980 evictInterference(VirtReg, BestPhys, NewVRegs);
998 SplitConstraints.resize(UseBlocks.
size());
1000 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1006 BC.
Entry = BI.
LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1007 BC.
Exit = BI.
LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1018 if (Intf.
first() <= Indexes->getMBBStartIdx(BC.
Number)) {
1019 BC.
Entry = SpillPlacement::MustSpill;
1022 BC.
Entry = SpillPlacement::PrefSpill;
1031 if (Intf.
last() >= SA->getLastSplitPoint(BC.
Number)) {
1032 BC.
Exit = SpillPlacement::MustSpill;
1035 BC.
Exit = SpillPlacement::PrefSpill;
1044 StaticCost += SpillPlacer->getBlockFrequency(BC.
Number);
1050 SpillPlacer->addConstraints(SplitConstraints);
1051 return SpillPlacer->scanActiveBundles();
1058 const unsigned GroupSize = 8;
1060 unsigned TBS[GroupSize];
1061 unsigned B = 0,
T = 0;
1063 for (
unsigned i = 0; i != Blocks.
size(); ++i) {
1064 unsigned Number = Blocks[i];
1068 assert(
T < GroupSize &&
"Array overflow");
1070 if (++
T == GroupSize) {
1077 assert(B < GroupSize &&
"Array overflow");
1081 if (Intf.
first() <= Indexes->getMBBStartIdx(Number))
1082 BCS[B].Entry = SpillPlacement::MustSpill;
1084 BCS[
B].
Entry = SpillPlacement::PrefSpill;
1087 if (Intf.
last() >= SA->getLastSplitPoint(Number))
1088 BCS[B].Exit = SpillPlacement::MustSpill;
1090 BCS[
B].
Exit = SpillPlacement::PrefSpill;
1092 if (++B == GroupSize) {
1102 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
1104 BitVector Todo = SA->getThroughBlocks();
1106 unsigned AddedTo = 0;
1108 unsigned Visited = 0;
1114 for (
int i = 0, e = NewBundles.
size(); i != e; ++i) {
1115 unsigned Bundle = NewBundles[i];
1121 if (!Todo.
test(Block))
1132 if (ActiveBlocks.
size() == AddedTo)
1137 auto NewBlocks =
makeArrayRef(ActiveBlocks).slice(AddedTo);
1139 addThroughConstraints(Cand.Intf, NewBlocks);
1143 SpillPlacer->addPrefSpill(NewBlocks,
true);
1144 AddedTo = ActiveBlocks.
size();
1147 SpillPlacer->iterate();
1159 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1161 if (!SA->getNumThroughBlocks())
1165 Cand.reset(IntfCache, 0);
1167 DEBUG(
dbgs() <<
"Compact region bundles");
1171 SpillPlacer->prepare(Cand.LiveBundles);
1175 if (!addSplitConstraints(Cand.Intf, Cost)) {
1181 SpillPlacer->finish();
1183 if (!Cand.LiveBundles.any()) {
1189 for (
int i : Cand.LiveBundles.set_bits())
1190 dbgs() <<
" EB#" << i;
1201 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1205 Cost += SpillPlacer->getBlockFrequency(Number);
1209 Cost += SpillPlacer->getBlockFrequency(Number);
1218 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1220 const BitVector &LiveBundles = Cand.LiveBundles;
1222 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1225 bool RegIn = LiveBundles[Bundles->getBundle(BC.
Number,
false)];
1226 bool RegOut = LiveBundles[Bundles->getBundle(BC.
Number,
true)];
1230 Ins += RegIn != (BC.
Entry == SpillPlacement::PrefReg);
1232 Ins += RegOut != (BC.
Exit == SpillPlacement::PrefReg);
1234 GlobalCost += SpillPlacer->getBlockFrequency(BC.
Number);
1237 for (
unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1238 unsigned Number = Cand.ActiveBlocks[i];
1239 bool RegIn = LiveBundles[Bundles->getBundle(Number,
false)];
1240 bool RegOut = LiveBundles[Bundles->getBundle(Number,
true)];
1241 if (!RegIn && !RegOut)
1243 if (RegIn && RegOut) {
1245 Cand.Intf.moveToBlock(Number);
1246 if (Cand.Intf.hasInterference()) {
1247 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1248 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1253 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1274 const unsigned NumGlobalIntvs = LREdit.
size();
1275 DEBUG(
dbgs() <<
"splitAroundRegion with " << NumGlobalIntvs <<
" globals.\n");
1276 assert(NumGlobalIntvs &&
"No global intervals configured");
1281 unsigned Reg = SA->getParent().reg;
1282 bool SingleInstrs = RegClassInfo.isProperSubClass(
MRI->getRegClass(Reg));
1286 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1289 unsigned IntvIn = 0, IntvOut = 0;
1292 unsigned CandIn = BundleCand[Bundles->getBundle(Number,
false)];
1294 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1295 IntvIn = Cand.IntvIdx;
1296 Cand.Intf.moveToBlock(Number);
1297 IntfIn = Cand.Intf.first();
1301 unsigned CandOut = BundleCand[Bundles->getBundle(Number,
true)];
1303 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1304 IntvOut = Cand.IntvIdx;
1305 Cand.Intf.moveToBlock(Number);
1306 IntfOut = Cand.Intf.last();
1311 if (!IntvIn && !IntvOut) {
1313 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1314 SE->splitSingleBlock(BI);
1318 if (IntvIn && IntvOut)
1319 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1321 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1323 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1329 BitVector Todo = SA->getThroughBlocks();
1330 for (
unsigned c = 0; c != UsedCands.
size(); ++c) {
1332 for (
unsigned i = 0, e = Blocks.
size(); i != e; ++i) {
1333 unsigned Number = Blocks[i];
1334 if (!Todo.
test(Number))
1338 unsigned IntvIn = 0, IntvOut = 0;
1341 unsigned CandIn = BundleCand[Bundles->getBundle(Number,
false)];
1343 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1344 IntvIn = Cand.IntvIdx;
1345 Cand.Intf.moveToBlock(Number);
1346 IntfIn = Cand.Intf.first();
1349 unsigned CandOut = BundleCand[Bundles->getBundle(Number,
true)];
1351 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1352 IntvOut = Cand.IntvIdx;
1353 Cand.Intf.moveToBlock(Number);
1354 IntfOut = Cand.Intf.last();
1356 if (!IntvIn && !IntvOut)
1358 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1365 SE->finish(&IntvMap);
1366 DebugVars->splitRegister(Reg, LREdit.
regs(), *LIS);
1368 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
1369 unsigned OrigBlocks = SA->getNumLiveBlocks();
1376 for (
unsigned i = 0, e = LREdit.
size(); i != e; ++i) {
1380 if (getStage(Reg) != RS_New)
1385 if (IntvMap[i] == 0) {
1386 setStage(Reg, RS_Spill);
1392 if (IntvMap[i] < NumGlobalIntvs) {
1393 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1394 DEBUG(
dbgs() <<
"Main interval covers the same " << OrigBlocks
1395 <<
" blocks as original.\n");
1397 setStage(Reg, RS_Split2);
1407 MF->verify(
this,
"After splitting live range around region");
1412 unsigned NumCands = 0;
1416 bool HasCompact = calcCompactRegion(GlobalCand.front());
1420 BestCost = BlockFrequency::getMaxFrequency();
1424 BestCost = calcSpillCost();
1425 DEBUG(
dbgs() <<
"Cost of isolating all blocks = ";
1426 MBFI->printBlockFreq(
dbgs(), BestCost) <<
'\n');
1430 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1434 if (!HasCompact && BestCand ==
NoCand)
1437 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1440 unsigned RAGreedy::calculateRegionSplitCost(
LiveInterval &VirtReg,
1445 unsigned BestCand =
NoCand;
1447 while (
unsigned PhysReg = Order.
next()) {
1448 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1453 if (NumCands == IntfCache.getMaxCursors()) {
1454 unsigned WorstCount = ~0u;
1456 for (
unsigned i = 0; i != NumCands; ++i) {
1457 if (i == BestCand || !GlobalCand[i].PhysReg)
1459 unsigned Count = GlobalCand[i].LiveBundles.count();
1460 if (Count < WorstCount) {
1466 GlobalCand[Worst] = GlobalCand[NumCands];
1467 if (BestCand == NumCands)
1471 if (GlobalCand.size() <= NumCands)
1472 GlobalCand.resize(NumCands+1);
1473 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1474 Cand.reset(IntfCache, PhysReg);
1476 SpillPlacer->prepare(Cand.LiveBundles);
1478 if (!addSplitConstraints(Cand.Intf, Cost)) {
1483 MBFI->printBlockFreq(
dbgs(), Cost));
1484 if (Cost >= BestCost) {
1487 dbgs() <<
" worse than no bundles\n";
1489 dbgs() <<
" worse than "
1490 <<
PrintReg(GlobalCand[BestCand].PhysReg, TRI) <<
'\n';
1496 SpillPlacer->finish();
1499 if (!Cand.LiveBundles.any()) {
1504 Cost += calcGlobalSplitCost(Cand);
1506 dbgs() <<
", total = "; MBFI->printBlockFreq(
dbgs(), Cost)
1508 for (
int i : Cand.LiveBundles.set_bits())
1509 dbgs() <<
" EB#" << i;
1512 if (Cost < BestCost) {
1513 BestCand = NumCands;
1521 unsigned RAGreedy::doRegionSplit(
LiveInterval &VirtReg,
unsigned BestCand,
1526 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
1530 BundleCand.assign(Bundles->getNumBundles(),
NoCand);
1533 if (BestCand !=
NoCand) {
1534 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1535 if (
unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1537 Cand.IntvIdx = SE->openIntv();
1539 << B <<
" bundles, intv " << Cand.IntvIdx <<
".\n");
1546 GlobalSplitCandidate &Cand = GlobalCand.front();
1547 assert(!Cand.PhysReg &&
"Compact region has no physreg");
1548 if (
unsigned B = Cand.getBundles(BundleCand, 0)) {
1550 Cand.IntvIdx = SE->openIntv();
1551 DEBUG(
dbgs() <<
"Split for compact region in " << B <<
" bundles, intv "
1552 << Cand.IntvIdx <<
".\n");
1557 splitAroundRegion(LREdit, UsedCands);
1570 assert(&SA->getParent() == &VirtReg &&
"Live range wasn't analyzed");
1571 unsigned Reg = VirtReg.
reg;
1572 bool SingleInstrs = RegClassInfo.isProperSubClass(
MRI->getRegClass(Reg));
1573 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
1576 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1578 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1579 SE->splitSingleBlock(BI);
1587 SE->finish(&IntvMap);
1590 DebugVars->splitRegister(Reg, LREdit.
regs(), *LIS);
1592 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
1596 for (
unsigned i = 0, e = LREdit.
size(); i != e; ++i) {
1598 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1599 setStage(LI, RS_Spill);
1603 MF->
verify(
this,
"After splitting live range around basic blocks");
1617 assert(SuperRC &&
"Invalid register class");
1639 if (!RegClassInfo.isProperSubClass(CurRC))
1644 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
1645 SE->reset(LREdit, SplitEditor::SM_Size);
1648 if (Uses.
size() <= 1)
1651 DEBUG(
dbgs() <<
"Split around " << Uses.
size() <<
" individual instrs.\n");
1654 TRI->getLargestLegalSuperClass(CurRC, *MF);
1655 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1660 for (
unsigned i = 0; i != Uses.
size(); ++i) {
1661 if (
const MachineInstr *
MI = Indexes->getInstructionFromIndex(Uses[i]))
1662 if (
MI->isFullCopy() ||
1663 SuperRCNumAllocatableRegs ==
1666 DEBUG(
dbgs() <<
" skip:\t" << Uses[i] <<
'\t' << *
MI);
1670 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1671 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1672 SE->useIntv(SegStart, SegStop);
1675 if (LREdit.
empty()) {
1676 DEBUG(
dbgs() <<
"All uses were copies.\n");
1681 SE->finish(&IntvMap);
1682 DebugVars->splitRegister(VirtReg.
reg, LREdit.
regs(), *LIS);
1683 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
1686 setStage(LREdit.
begin(), LREdit.
end(), RS_Spill);
1699 void RAGreedy::calcGapWeights(
unsigned PhysReg,
1701 assert(SA->getUseBlocks().size() == 1 &&
"Not a local interval");
1704 const unsigned NumGaps = Uses.
size()-1;
1708 BI.LiveIn ? BI.FirstInstr.
getBaseIndex() : BI.FirstInstr;
1712 GapWeight.
assign(NumGaps, 0.0f);
1716 if (!
Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1717 .checkInterference())
1728 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1729 for (
unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1731 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1732 if (++Gap == NumGaps)
1738 const float weight = IntI.value()->weight;
1739 for (; Gap != NumGaps; ++Gap) {
1740 GapWeight[Gap] =
std::max(GapWeight[Gap], weight);
1741 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1751 const LiveRange &LR = LIS->getRegUnit(*Units);
1756 for (
unsigned Gap = 0; I != E && I->start < StopIdx; ++
I) {
1757 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1758 if (++Gap == NumGaps)
1763 for (; Gap != NumGaps; ++Gap) {
1765 if (Uses[Gap+1].getBaseIndex() >= I->
end)
1779 assert(SA->getUseBlocks().size() == 1 &&
"Not a local interval");
1790 if (Uses.
size() <= 2)
1792 const unsigned NumGaps = Uses.
size()-1;
1795 dbgs() <<
"tryLocalSplit: ";
1796 for (
unsigned i = 0, e = Uses.
size(); i != e; ++i)
1797 dbgs() <<
' ' << Uses[i];
1804 if (
Matrix->checkRegMaskInterference(VirtReg)) {
1809 unsigned ri = std::lower_bound(RMS.
begin(), RMS.
end(),
1811 unsigned re = RMS.
size();
1812 for (
unsigned i = 0; i != NumGaps && ri != re; ++i) {
1814 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1815 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1819 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1821 DEBUG(
dbgs() <<
' ' << RMS[ri] <<
':' << Uses[i] <<
'-' << Uses[i+1]);
1822 RegMaskGaps.push_back(i);
1825 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1849 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1852 unsigned BestBefore = NumGaps;
1853 unsigned BestAfter = 0;
1856 const float blockFreq =
1857 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1858 (1.0f / MBFI->getEntryFreq());
1862 while (
unsigned PhysReg = Order.
next()) {
1865 calcGapWeights(PhysReg, GapWeight);
1868 if (
Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1869 for (
unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1880 float MaxGap = GapWeight[0];
1884 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1885 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1888 << Uses[SplitBefore] <<
'-' << Uses[SplitAfter]
1889 <<
" i=" << MaxGap);
1892 if (!LiveBefore && !LiveAfter) {
1900 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1903 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1912 blockFreq * (NewGaps + 1),
1913 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1914 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
1921 float Diff = EstWeight - MaxGap;
1922 if (Diff > BestDiff) {
1926 BestAfter = SplitAfter;
1933 if (++SplitBefore < SplitAfter) {
1936 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1938 for (
unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1939 MaxGap =
std::max(MaxGap, GapWeight[i]);
1947 if (SplitAfter >= NumGaps) {
1953 MaxGap =
std::max(MaxGap, GapWeight[SplitAfter++]);
1958 if (BestBefore == NumGaps)
1961 DEBUG(
dbgs() <<
"Best local split range: " << Uses[BestBefore]
1962 <<
'-' << Uses[BestAfter] <<
", " << BestDiff
1963 <<
", " << (BestAfter - BestBefore + 1) <<
" instrs\n");
1965 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
1969 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1970 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1971 SE->useIntv(SegStart, SegStop);
1973 SE->finish(&IntvMap);
1974 DebugVars->splitRegister(VirtReg.
reg, LREdit.
regs(), *LIS);
1979 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1980 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1981 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1982 if (NewGaps >= NumGaps) {
1983 DEBUG(
dbgs() <<
"Tagging non-progress ranges: ");
1984 assert(!ProgressRequired &&
"Didn't make progress when it was required.");
1985 for (
unsigned i = 0, e = IntvMap.
size(); i != e; ++i)
1986 if (IntvMap[i] == 1) {
1987 setStage(LIS->getInterval(LREdit.
get(i)), RS_Split2);
2007 if (getStage(VirtReg) >= RS_Spill)
2011 if (LIS->intervalIsInOneMBB(VirtReg)) {
2014 SA->analyze(&VirtReg);
2015 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2016 if (PhysReg || !NewVRegs.
empty())
2018 return tryInstructionSplit(VirtReg, Order, NewVRegs);
2024 SA->analyze(&VirtReg);
2030 if (SA->didRepairRange()) {
2032 Matrix->invalidateVirtRegs();
2033 if (
unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
2040 if (getStage(VirtReg) < RS_Split2) {
2041 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2042 if (PhysReg || !NewVRegs.
empty())
2047 return tryBlockSplit(VirtReg, Order, NewVRegs);
2063 RAGreedy::mayRecolorAllInterferences(
unsigned PhysReg,
LiveInterval &VirtReg,
2064 SmallLISet &RecoloringCandidates,
2065 const SmallVirtRegSet &FixedRegisters) {
2074 DEBUG(
dbgs() <<
"Early abort: too many interferences.\n");
2075 CutOffInfo |= CO_Interf;
2082 if ((getStage(*Intf) == RS_Done &&
2083 MRI->getRegClass(Intf->
reg) == CurRC) ||
2084 FixedRegisters.count(Intf->
reg)) {
2085 DEBUG(
dbgs() <<
"Early abort: the inteference is not recolorable.\n");
2088 RecoloringCandidates.insert(Intf);
2133 unsigned RAGreedy::tryLastChanceRecoloring(
LiveInterval &VirtReg,
2136 SmallVirtRegSet &FixedRegisters,
2138 DEBUG(
dbgs() <<
"Try last chance recoloring for " << VirtReg <<
'\n');
2141 "Last chance recoloring should really be last chance");
2147 DEBUG(
dbgs() <<
"Abort because max depth has been reached.\n");
2148 CutOffInfo |= CO_Depth;
2153 SmallLISet RecoloringCandidates;
2163 while (
unsigned PhysReg = Order.
next()) {
2164 DEBUG(
dbgs() <<
"Try to assign: " << VirtReg <<
" to "
2165 <<
PrintReg(PhysReg, TRI) <<
'\n');
2166 RecoloringCandidates.clear();
2167 VirtRegToPhysReg.
clear();
2168 CurrentNewVRegs.
clear();
2171 if (
Matrix->checkInterference(VirtReg, PhysReg) >
2172 LiveRegMatrix::IK_VirtReg) {
2173 DEBUG(
dbgs() <<
"Some inteferences are not with virtual registers.\n");
2180 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2182 DEBUG(
dbgs() <<
"Some inteferences cannot be recolored.\n");
2189 PQueue RecoloringQueue;
2190 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2191 EndIt = RecoloringCandidates.end();
2192 It != EndIt; ++It) {
2193 unsigned ItVirtReg = (*It)->reg;
2194 enqueue(RecoloringQueue, *It);
2195 assert(VRM->hasPhys(ItVirtReg) &&
2196 "Interferences are supposed to be with allocated vairables");
2199 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2207 Matrix->assign(VirtReg, PhysReg);
2212 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2213 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2214 FixedRegisters, Depth)) {
2216 for (
unsigned NewVReg : CurrentNewVRegs)
2220 Matrix->unassign(VirtReg);
2224 DEBUG(
dbgs() <<
"Fail to assign: " << VirtReg <<
" to "
2225 <<
PrintReg(PhysReg, TRI) <<
'\n');
2228 FixedRegisters = SaveFixedRegisters;
2229 Matrix->unassign(VirtReg);
2236 End = CurrentNewVRegs.end();
2237 Next !=
End; ++Next) {
2238 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
2243 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2244 EndIt = RecoloringCandidates.end();
2245 It != EndIt; ++It) {
2246 unsigned ItVirtReg = (*It)->reg;
2247 if (VRM->hasPhys(ItVirtReg))
2249 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2250 Matrix->assign(**It, ItPhysReg);
2266 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2268 SmallVirtRegSet &FixedRegisters,
2270 while (!RecoloringQueue.empty()) {
2272 DEBUG(
dbgs() <<
"Try to recolor: " << *LI <<
'\n');
2274 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2279 if (PhysReg == ~0u || (!PhysReg && !LI->
empty()))
2283 assert(LI->
empty() &&
"Only empty live-range do not require a register");
2284 DEBUG(
dbgs() <<
"Recoloring of " << *LI <<
" succeeded. Empty LI.\n");
2288 <<
" succeeded with: " <<
PrintReg(PhysReg, TRI) <<
'\n');
2290 Matrix->assign(*LI, PhysReg);
2291 FixedRegisters.insert(LI->
reg);
2300 unsigned RAGreedy::selectOrSplit(
LiveInterval &VirtReg,
2302 CutOffInfo = CO_None;
2303 LLVMContext &Ctx = MF->getFunction()->getContext();
2304 SmallVirtRegSet FixedRegisters;
2305 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2306 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2307 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2308 if (CutOffEncountered == CO_Depth)
2309 Ctx.
emitError(
"register allocation failed: maximum depth for recoloring "
2310 "reached. Use -fexhaustive-register-search to skip "
2312 else if (CutOffEncountered == CO_Interf)
2313 Ctx.
emitError(
"register allocation failed: maximum interference for "
2314 "recoloring reached. Use -fexhaustive-register-search "
2316 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2317 Ctx.
emitError(
"register allocation failed: maximum interference and "
2318 "depth for recoloring reached. Use "
2319 "-fexhaustive-register-search to skip cutoffs");
2330 unsigned RAGreedy::tryAssignCSRFirstTime(
LiveInterval &VirtReg,
2333 unsigned &CostPerUseLimit,
2335 if (getStage(VirtReg) == RS_Spill && VirtReg.
isSpillable()) {
2338 SA->analyze(&VirtReg);
2339 if (calcSpillCost() >= CSRCost)
2344 CostPerUseLimit = 1;
2347 if (getStage(VirtReg) < RS_Split) {
2350 SA->analyze(&VirtReg);
2351 unsigned NumCands = 0;
2353 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2360 doRegionSplit(VirtReg, BestCand,
false, NewVRegs);
2366 void RAGreedy::aboutToRemoveInterval(
LiveInterval &LI) {
2368 SetOfBrokenHints.remove(&LI);
2371 void RAGreedy::initializeCSRCost() {
2376 if (!CSRCost.getFrequency())
2380 uint64_t ActualEntry = MBFI->getEntryFreq();
2385 uint64_t FixedEntry = 1 << 14;
2386 if (ActualEntry < FixedEntry)
2388 else if (ActualEntry <= UINT32_MAX)
2393 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2399 void RAGreedy::collectHintInfo(
unsigned Reg, HintsInfo &Out) {
2401 if (!Instr.isFullCopy())
2404 unsigned OtherReg = Instr.getOperand(0).getReg();
2405 if (OtherReg == Reg) {
2406 OtherReg = Instr.getOperand(1).getReg();
2407 if (OtherReg == Reg)
2411 unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
2413 : VRM->getPhys(OtherReg);
2415 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2426 for (
const HintInfo &Info : List) {
2427 if (Info.PhysReg != PhysReg)
2441 void RAGreedy::tryHintRecoloring(
LiveInterval &VirtReg) {
2448 unsigned Reg = VirtReg.
reg;
2449 unsigned PhysReg = VRM->getPhys(Reg);
2456 <<
PrintReg(PhysReg, TRI) <<
")\n");
2462 if (TargetRegisterInfo::isPhysicalRegister(Reg))
2465 assert(VRM->hasPhys(Reg) &&
"We have unallocated variable!!");
2470 unsigned CurrPhys = VRM->getPhys(Reg);
2473 if (CurrPhys != PhysReg && (!
MRI->getRegClass(Reg)->contains(PhysReg) ||
2474 Matrix->checkInterference(LI, PhysReg)))
2478 <<
") is recolorable.\n");
2482 collectHintInfo(Reg, Info);
2485 if (CurrPhys != PhysReg) {
2486 DEBUG(
dbgs() <<
"Checking profitability:\n");
2487 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2490 <<
"\nNew Cost: " << NewCopiesCost.
getFrequency() <<
'\n');
2491 if (OldCopiesCost < NewCopiesCost) {
2492 DEBUG(
dbgs() <<
"=> Not profitable.\n");
2501 Matrix->assign(LI, PhysReg);
2505 for (
const HintInfo &
HI : Info) {
2509 }
while (!RecoloringCandidates.
empty());
2548 void RAGreedy::tryHintsRecoloring() {
2550 assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
2551 "Recoloring is possible only for virtual registers");
2554 if (!VRM->hasPhys(LI->reg))
2556 tryHintRecoloring(*LI);
2560 unsigned RAGreedy::selectOrSplitImpl(
LiveInterval &VirtReg,
2562 SmallVirtRegSet &FixedRegisters,
2564 unsigned CostPerUseLimit = ~0u;
2567 if (
unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2571 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
2573 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2574 CostPerUseLimit, NewVRegs);
2575 if (CSRReg || !NewVRegs.
empty())
2583 LiveRangeStage Stage = getStage(VirtReg);
2585 <<
" Cascade " << ExtraRegInfo[VirtReg.
reg].Cascade <<
'\n');
2590 if (Stage != RS_Split)
2591 if (
unsigned PhysReg =
2592 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
2593 unsigned Hint =
MRI->getSimpleHint(VirtReg.
reg);
2599 if (Hint && Hint != PhysReg)
2600 SetOfBrokenHints.insert(&VirtReg);
2604 assert((NewVRegs.
empty() ||
Depth) &&
"Cannot append to existing NewVRegs");
2609 if (Stage < RS_Split) {
2610 setStage(VirtReg, RS_Split);
2611 DEBUG(
dbgs() <<
"wait for second round\n");
2616 if (Stage < RS_Spill) {
2618 unsigned NewVRegSizeBefore = NewVRegs.
size();
2619 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2620 if (PhysReg || (NewVRegs.
size() - NewVRegSizeBefore))
2627 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2636 setStage(VirtReg, RS_Memory);
2637 DEBUG(
dbgs() <<
"Do as if this register is in memory\n");
2642 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
2643 spiller().spill(LRE);
2644 setStage(NewVRegs.
begin(), NewVRegs.
end(), RS_Done);
2647 MF->verify(
this,
"After spilling");
2655 void RAGreedy::reportNumberOfSplillsReloads(
MachineLoop *
L,
unsigned &Reloads,
2656 unsigned &FoldedReloads,
2658 unsigned &FoldedSpills) {
2666 unsigned SubReloads;
2667 unsigned SubFoldedReloads;
2669 unsigned SubFoldedSpills;
2671 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
2672 SubSpills, SubFoldedSpills);
2673 Reloads += SubReloads;
2674 FoldedReloads += SubFoldedReloads;
2675 Spills += SubSpills;
2676 FoldedSpills += SubFoldedSpills;
2685 if (
Loops->getLoopFor(MBB) ==
L)
2702 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
2703 using namespace ore;
2706 L->getStartLoc(), L->getHeader());
2708 R <<
NV(
"NumSpills", Spills) <<
" spills ";
2710 R <<
NV(
"NumFoldedSpills", FoldedSpills) <<
" folded spills ";
2712 R <<
NV(
"NumReloads", Reloads) <<
" reloads ";
2714 R <<
NV(
"NumFoldedReloads", FoldedReloads) <<
" folded reloads ";
2715 ORE->emit(R <<
"generated in loop");
2720 DEBUG(
dbgs() <<
"********** GREEDY REGISTER ALLOCATION **********\n"
2721 <<
"********** Function: " << mf.
getName() <<
'\n');
2725 TII = MF->getSubtarget().getInstrInfo();
2726 RCI.runOnMachineFunction(mf);
2729 MF->getSubtarget().enableRALocalReassignment(
2730 MF->getTarget().getOptLevel());
2733 MF->verify(
this,
"Before greedy register allocator");
2736 getAnalysis<LiveIntervals>(),
2737 getAnalysis<LiveRegMatrix>());
2738 Indexes = &getAnalysis<SlotIndexes>();
2739 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2740 DomTree = &getAnalysis<MachineDominatorTree>();
2741 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2743 Loops = &getAnalysis<MachineLoopInfo>();
2744 Bundles = &getAnalysis<EdgeBundles>();
2745 SpillPlacer = &getAnalysis<SpillPlacement>();
2746 DebugVars = &getAnalysis<LiveDebugVariables>();
2747 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2749 initializeCSRCost();
2756 SE.reset(
new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
2757 ExtraRegInfo.clear();
2758 ExtraRegInfo.resize(
MRI->getNumVirtRegs());
2760 IntfCache.init(MF,
Matrix->getLiveUnions(), Indexes, LIS, TRI);
2761 GlobalCand.resize(32);
2762 SetOfBrokenHints.clear();
2765 tryHintsRecoloring();
2767 reportNumberOfSplillsReloads();
void push_back(const T &Elt)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
DiagnosticInfoOptimizationBase::Argument NV
void rewind()
Start over from the beginning.
STATISTIC(NumFunctions,"Total number of functions")
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
int getInstrDistance(SlotIndex other) const
Return the scaled distance from this index to the given one, where all slots on the same instruction ...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
const T & front() const
front - Get the first element.
std::pair< std::string, std::string > SplitBefore(std::string X, std::string S)
LiveInterval - This class represents the liveness of a register, or stack slot.
ArrayRef< MCPhysReg > getOrder() const
Get the allocation order without reordered hints.
bool isSpillable() const
isSpillable - Can this interval be spilled?
SM_Speed - Overlap intervals to minimize the expected execution frequency of the inserted copies...
LiveSegments::iterator SegmentIter
SlotIndex FirstDef
First non-phi valno->def, or SlotIndex().
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
unsigned next(unsigned Limit=0)
Return the next physical register in the allocation order, or 0.
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
char & RAGreedyID
Greedy register allocator.
Callback methods for LiveRangeEdit owners.
This class represents the liveness of a register, stack slot, etc.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
A description of a memory reference used in the backend.
Query interferences between a single live virtual register and a live interval union.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
static cl::opt< unsigned > LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden, cl::desc("Last chance recoloring max depth"), cl::init(5))
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
This class is basically a combination of TimeRegion and Timer.
Reg
All possible values of the reg field in the ModR/M byte.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
unsigned getSize() const
getSize - Returns the sum of sizes of all the LiveRange's.
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
LLVM_NODISCARD bool empty() const
BorderConstraint Exit
Constraint on block exit.
void assign(size_type NumElts, const T &Elt)
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
SplitEditor - Edit machine code and LiveIntervals for live range splitting.
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
RegisterRegAlloc class - Track the registration of register allocators.
BlockConstraint - Entry and exit constraints for a basic block.
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
size_t size() const
size - Get the array size.
virtual bool hasLoadFromStackSlot(const MachineInstr &MI, const MachineMemOperand *&MMO, int &FrameIndex) const
If the specified machine instruction has a load from a stack slot, return true along with the FrameIn...
SlotIndex LastInstr
Last instr accessing current reg.
unsigned get(unsigned idx) const
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
TargetInstrInfo - Interface to description of machine instruction set.
static cl::opt< unsigned > CSRFirstTimeCost("regalloc-csr-first-time-cost", cl::desc("Cost for first time use of callee-saved register."), cl::init(0), cl::Hidden)
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")), cl::init(SplitEditor::SM_Speed))
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
SlotIndex last()
last - Return the ending index of the last interfering range in the current block.
initializer< Ty > init(const Ty &Val)
const uint8_t AllocationPriority
Classes with a higher priority value are assigned first by register allocators using a greedy heurist...
bool isValid() const
Returns true if this is a valid index.
unsigned const MachineRegisterInfo * MRI
This is an important class for using LLVM in a threaded context.
Cursor - The primary query interface for the block interference cache.
SM_Partition(Default) - Try to create the complement interval so it doesn't overlap any other interva...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
SM_Size - Overlap intervals to minimize the number of inserted COPY instructions. ...
INITIALIZE_PASS_BEGIN(RAGreedy,"greedy","Greedy Register Allocator", false, false) INITIALIZE_PASS_END(RAGreedy
Represent the analysis usage information of a pass.
Greedy Register Allocator
static unsigned getNumAllocatableRegsForConstraints(const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, const RegisterClassInfo &RCI)
Get the number of allocatable registers that match the constraints of Reg on MI and that are also in ...
unsigned Number
Basic block number (from MBB::getNumber()).
virtual unsigned isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
void resize(typename StorageT::size_type s)
static const unsigned End
FunctionPass class - This class is used to implement most global optimizations.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
BorderConstraint Entry
Constraint on block entry.
static cl::opt< bool > EnableLocalReassignment("enable-local-reassign", cl::Hidden, cl::desc("Local reassignment can yield better allocation decisions, but ""may be compile time intensive"), cl::init(false))
const T & back() const
back - Get the last element.
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
static cl::opt< unsigned > LastChanceRecoloringMaxInterference("lcr-max-interf", cl::Hidden, cl::desc("Last chance recoloring maximum number of considered"" interference at a time"), cl::init(8))
A SetVector that performs no allocations if smaller than a certain size.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, VirtRegMap *VRM, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
Segments::const_iterator const_iterator
SlotIndex FirstInstr
First instr accessing current reg.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool test(unsigned Idx) const
Additional information about basic blocks where the current variable is live.
Promote Memory to Register
SplitAnalysis - Analyze a LiveInterval, looking for live range splitting opportunities.
LLVM_NODISCARD T pop_back_val()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
bool hasInterference()
hasInterference - Return true if the current block has any interference.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
virtual unsigned isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct load from a stack slot, return the virtual or physic...
static RegisterRegAlloc greedyRegAlloc("greedy","greedy register allocator", createGreedyRegisterAllocator)
unsigned getNumRegs() const
Return the number of registers in this class.
bool LiveOut
Current reg is live out.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void moveToBlock(unsigned MBBNum)
moveTo - Move cursor to basic block MBBNum.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
MachineFunctionProperties & set(Property P)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Representation of each machine instruction.
ArrayRef< unsigned > regs() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
const TargetRegisterClass * getRegClassConstraintEffectForVReg(unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, bool ExploreBundle=false) const
Applies the constraints (def/use) implied by this MI on Reg to the given CurRC.
void verify(const MachineRegisterInfo *MRI=nullptr) const
Walks the interval and assert if any invariants fail to hold.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
static cl::opt< bool > EnableDeferredSpilling("enable-deferred-spilling", cl::Hidden, cl::desc("Instead of spilling a variable right away, defer the actual ""code insertion to the end of the allocation. That way the ""allocator might still find a suitable coloring for this ""variable because of other evicted variables."), cl::init(false))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static float normalizeSpillWeight(float UseDefFreq, unsigned Size, unsigned NumInstr)
Normalize the spill weight of a live interval.
bool operator<(int64_t V1, const APSInt &V2)
bool isHint() const
Return true if the last register returned from next() was a preferred register.
virtual bool hasStoreToStackSlot(const MachineInstr &MI, const MachineMemOperand *&MMO, int &FrameIndex) const
If the specified machine instruction has a store to a stack slot, return true along with the FrameInd...
static cl::opt< bool > ExhaustiveSearch("exhaustive-register-search", cl::NotHidden, cl::desc("Exhaustive Search for registers bypassing the depth ""and interference cutoffs of last chance recoloring"))
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
bool LiveIn
Current reg is live in.
SlotIndex - An opaque wrapper around machine indexes.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
SlotIndex first()
first - Return the starting index of the first interfering range in the current block.
Properties which a MachineFunction may have at a given point in time.
bool ChangesValue
True when this block changes the value of the live range.