62 #define DEBUG_TYPE "regalloc" 64 STATISTIC(numJoins ,
"Number of interval joins performed");
65 STATISTIC(numCrossRCs ,
"Number of cross class joins performed");
66 STATISTIC(numCommutes ,
"Number of instruction commuting performed");
67 STATISTIC(numExtends ,
"Number of copies extended");
68 STATISTIC(NumReMats ,
"Number of instructions re-materialized");
69 STATISTIC(NumInflated ,
"Number of register classes inflated");
70 STATISTIC(NumLaneConflicts,
"Number of dead lane conflicts tested");
71 STATISTIC(NumLaneResolves,
"Number of dead lane conflicts resolved");
74 cl::desc(
"Coalesce copies (default=true)"),
89 cl::desc(
"Coalesce copies that span blocks (default=subtarget)"),
94 cl::desc(
"Verify machine instrs before and after register coalescing"),
116 bool ShrinkMainRange;
120 bool JoinGlobalCopies;
141 void eliminateDeadDefs();
147 void coalesceLocals();
150 void joinAllIntervals();
224 void updateRegDefsUses(
unsigned SrcReg,
unsigned DstReg,
unsigned SubIdx);
288 void releaseMemory()
override;
304 "Simple Register Coalescing",
false,
false)
313 unsigned &Src,
unsigned &Dst,
314 unsigned &SrcSub,
unsigned &DstSub) {
316 Dst = MI->getOperand(0).getReg();
317 DstSub = MI->getOperand(0).getSubReg();
318 Src = MI->getOperand(1).getReg();
319 SrcSub = MI->getOperand(1).getSubReg();
320 }
else if (MI->isSubregToReg()) {
321 Dst = MI->getOperand(0).getReg();
322 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
323 MI->getOperand(3).getImm());
324 Src = MI->getOperand(2).getReg();
325 SrcSub = MI->getOperand(2).getSubReg();
340 for (
const auto &MI : *MBB) {
351 Flipped = CrossClass =
false;
353 unsigned Src, Dst, SrcSub, DstSub;
354 if (!
isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
356 Partial = SrcSub || DstSub;
373 if (!Dst)
return false;
380 if (!Dst)
return false;
390 if (SrcSub && DstSub) {
392 if (Src == Dst && SrcSub != DstSub)
418 if (DstIdx && !SrcIdx) {
424 CrossClass = NewRC != DstRC || NewRC != SrcRC;
429 "Cannot have a physical SubIdx");
447 unsigned Src, Dst, SrcSub, DstSub;
448 if (!
isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
455 }
else if (Src != SrcReg) {
463 assert(!DstIdx && !SrcIdx &&
"Inconsistent CoalescerPair state.");
469 return DstReg == Dst;
471 return TRI.
getSubReg(DstReg, SrcSub) == Dst;
482 void RegisterCoalescer::getAnalysisUsage(
AnalysisUsage &AU)
const {
494 void RegisterCoalescer::eliminateDeadDefs() {
500 void RegisterCoalescer::LRE_WillEraseInstruction(
MachineInstr *MI) {
508 assert(!CP.
isPhys() &&
"This doesn't work for physreg copies.");
533 if (BS == IntB.
end())
return false;
534 VNInfo *BValNo = BS->valno;
539 if (BValNo->
def != CopyIdx)
return false;
545 if (AS == IntA.end())
return false;
546 VNInfo *AValNo = AS->valno;
558 if (ValS == IntB.
end())
571 if (ValS+1 != BS)
return false;
575 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
579 BValNo->
def = FillerStart;
587 if (BValNo != ValS->valno)
596 S.removeSegment(*SS,
true);
599 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
602 if (SubBValNo != SubValSNo)
603 S.MergeValueNumberInto(SubBValNo, SubValSNo);
619 bool RecomputeLiveRange = AS->end == CopyIdx;
620 if (!RecomputeLiveRange) {
623 if (SS != S.end() && SS->end == CopyIdx) {
624 RecomputeLiveRange =
true;
629 if (RecomputeLiveRange)
636 bool RegisterCoalescer::hasOtherReachingDefs(
LiveInterval &IntA,
646 if (ASeg.
valno != AValNo)
continue;
649 if (BI != IntB.
begin())
651 for (; BI != IntB.
end() && ASeg.
end >= BI->start; ++BI) {
652 if (BI->valno == BValNo)
654 if (BI->start <= ASeg.
start && BI->end > ASeg.
start)
656 if (BI->start > ASeg.
start && BI->start < ASeg.
end)
668 if (S.
valno != SrcValNo)
674 bool RegisterCoalescer::removeCopyByCommutingDef(
const CoalescerPair &CP,
707 assert(BValNo !=
nullptr && BValNo->
def == CopyIdx);
741 unsigned NewReg = NewDstMO.
getReg();
747 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
757 if (US == IntA.end() || US->valno != AValNo)
778 if (NewMI != DefMI) {
811 assert(US != IntA.end() &&
"Use must be live");
812 if (US->valno != AValNo)
838 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
841 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
843 S.MergeValueNumberInto(SubDVNI, SubBValNo);
853 if (!IntA.hasSubRanges()) {
855 IntA.createSubRangeFrom(Allocator, Mask, IntA);
859 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
860 assert(ASubValNo !=
nullptr);
864 VNInfo *BSubValNo = SR.empty()
865 ? SR.getNextValue(CopyIdx, Allocator)
866 : SR.getVNInfoAt(CopyIdx);
867 assert(BSubValNo != nullptr);
868 addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
873 BValNo->
def = AValNo->
def;
931 bool RegisterCoalescer::removePartialRedundancy(
const CoalescerPair &CP,
962 bool FoundReverseCopy =
false;
981 bool ValB_Changed =
false;
982 for (
auto VNI : IntB.
valnos) {
994 FoundReverseCopy =
true;
998 if (!FoundReverseCopy)
1008 if (CopyLeftBB && CopyLeftBB->
succ_size() > 1)
1019 if (InsPos != CopyLeftBB->
end()) {
1025 LLVM_DEBUG(
dbgs() <<
"\tremovePartialRedundancy: Move the copy to " 1030 TII->
get(TargetOpcode::COPY), IntB.
reg)
1041 ErasedInstrs.
erase(NewCopyMI);
1043 LLVM_DEBUG(
dbgs() <<
"\tremovePartialRedundancy: Remove the copy from " 1052 deleteInstr(&CopyMI);
1066 VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
1067 assert(BValNo &&
"All sublanes should be live");
1073 shrinkToUses(&IntB);
1076 shrinkToUses(&IntA);
1084 "This code cannot handle physreg aliasing");
1086 if (!
Op.isReg() || !
Op.isDef() ||
Op.getReg() !=
Reg)
1090 if (
Op.getSubReg() == 0 ||
Op.isUndef())
1096 bool RegisterCoalescer::reMaterializeTrivialDef(
const CoalescerPair &CP,
1110 assert(ValNo &&
"CopyMI input register not live");
1126 bool SawStore =
false;
1134 unsigned CopyDstReg = DstOperand.
getReg();
1143 if (SrcIdx && DstIdx)
1149 unsigned NewDstReg = DstReg;
1154 NewDstReg = TRI->
getSubReg(DstReg, NewDstIdx);
1164 "Only expect to deal with virtual or physical registers");
1172 TII->
reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI);
1186 &&
"Shouldn't have SrcIdx+DstIdx at this point");
1190 if (CommonRC !=
nullptr) {
1209 assert(MO.
isImplicit() &&
"No explicit operands after implicit operands.");
1218 ErasedInstrs.
insert(CopyMI);
1238 if (DefRC !=
nullptr) {
1243 assert(NewRC &&
"subreg chosen for remat incompatible with instruction");
1253 updateRegDefsUses(DstReg, DstReg, DstIdx);
1281 if (!SR.liveAt(DefIndex))
1282 SR.createDeadDef(DefIndex, Alloc);
1283 MaxMask &= ~SR.LaneMask;
1285 if (MaxMask.
any()) {
1303 bool UpdatedSubRanges =
false;
1305 if ((SR.LaneMask & DstMask).none()) {
1307 <<
"Removing undefined SubRange " 1311 SR.removeValNo(RmValNo);
1312 UpdatedSubRanges =
true;
1316 if (UpdatedSubRanges)
1323 "Only expect virtual or physical registers in remat");
1326 CopyDstReg,
true ,
true ,
false ));
1358 for (
unsigned i = 0, e = NewMIImplDefs.
size(); i != e; ++i) {
1359 unsigned Reg = NewMIImplDefs[i];
1369 shrinkToUses(&SrcInt, &DeadDefs);
1370 if (!DeadDefs.
empty()) {
1376 UseMO.setReg(DstReg);
1383 eliminateDeadDefs();
1401 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1402 isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1410 if ((SR.LaneMask & SrcMask).none())
1415 }
else if (SrcLI.
liveAt(Idx))
1423 assert(Seg !=
nullptr &&
"No segment for defining instruction");
1425 if (V->isPHIDef()) {
1426 CopyMI->
setDesc(TII->
get(TargetOpcode::IMPLICIT_DEF));
1449 if ((SR.LaneMask & DstMask).none())
1452 VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1454 SR.removeValNo(SVNI);
1471 if ((SR.LaneMask & UseMask).none())
1473 if (SR.liveAt(UseIdx)) {
1479 isLive = DstLI.
liveAt(UseIdx);
1482 MO.setIsUndef(
true);
1492 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1493 MO.setIsUndef(
true);
1504 bool IsUndef =
true;
1506 if ((S.LaneMask & Mask).none())
1508 if (S.liveAt(UseIdx)) {
1521 ShrinkMainRange =
true;
1525 void RegisterCoalescer::updateRegDefsUses(
unsigned SrcReg,
1531 if (DstInt && DstInt->
hasSubRanges() && DstReg != SrcReg) {
1534 if (SubReg == 0 || MO.
isUndef())
1540 addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1555 if (SrcReg == DstReg && !Visited.
insert(UseMI).second)
1564 if (DstInt && !Reads && SubIdx && !UseMI->
isDebugValue())
1568 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1574 if (SubIdx && MO.
isDef())
1589 addUndefFlag(*DstInt, UseIdx, MO, SubIdx);
1599 dbgs() <<
"\t\tupdated: ";
1607 bool RegisterCoalescer::canJoinPhys(
const CoalescerPair &CP) {
1612 LLVM_DEBUG(
dbgs() <<
"\tCan only merge into reserved registers.\n");
1621 dbgs() <<
"\tCannot join complex intervals into reserved register.\n");
1625 bool RegisterCoalescer::joinCopy(
MachineInstr *CopyMI,
bool &Again) {
1630 if (!CP.setRegisters(CopyMI)) {
1635 if (CP.getNewRC()) {
1638 unsigned SrcIdx = CP.getSrcIdx();
1639 unsigned DstIdx = CP.getDstIdx();
1640 if (CP.isFlipped()) {
1645 CP.getNewRC(), *LIS)) {
1657 eliminateDeadDefs();
1664 if (
MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
1665 if (UndefMI->isImplicitDef())
1667 deleteInstr(CopyMI);
1675 if (CP.getSrcReg() == CP.getDstReg()) {
1677 LLVM_DEBUG(
dbgs() <<
"\tCopy already coalesced: " << LI <<
'\n');
1682 assert(ReadVNI &&
"No value before copy and no <undef> flag.");
1683 assert(ReadVNI != DefVNI &&
"Cannot read and define the same value.");
1691 S.MergeValueNumberInto(SDefVNI, SReadVNI);
1696 deleteInstr(CopyMI);
1704 <<
printReg(CP.getDstReg(),
TRI, CP.getSrcIdx()) <<
'\n');
1705 if (!canJoinPhys(CP)) {
1709 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1722 dbgs() <<
"\tConsidering merging to " 1724 if (CP.getDstIdx() && CP.getSrcIdx())
1727 <<
printReg(CP.getSrcReg()) <<
" in " 1731 <<
printReg(CP.getDstReg(),
TRI, CP.getSrcIdx()) <<
'\n';
1736 ShrinkMainRange =
false;
1742 if (!joinIntervals(CP)) {
1748 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1753 if (!CP.isPartial() && !CP.isPhys()) {
1754 if (adjustCopiesBackFrom(CP, CopyMI) ||
1755 removeCopyByCommutingDef(CP, CopyMI)) {
1756 deleteInstr(CopyMI);
1764 if (!CP.isPartial() && !CP.isPhys())
1765 if (removePartialRedundancy(CP, *CopyMI))
1776 if (CP.isCrossClass()) {
1789 ErasedInstrs.
erase(CopyMI);
1794 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1795 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1798 if (ShrinkMask.any()) {
1801 if ((S.LaneMask & ShrinkMask).none())
1809 if (ShrinkMainRange) {
1822 dbgs() <<
"\tSuccess: " <<
printReg(CP.getSrcReg(),
TRI, CP.getSrcIdx())
1823 <<
" -> " <<
printReg(CP.getDstReg(),
TRI, CP.getDstIdx()) <<
'\n';
1824 dbgs() <<
"\tResult = ";
1836 bool RegisterCoalescer::joinReservedPhysReg(
CoalescerPair &CP) {
1844 assert(RHS.containsOneValue() &&
"Invalid join with reserved register");
1870 !RegMaskUsable.
test(DstReg)) {
1933 <<
printReg(DstReg, TRI) <<
" at " << CopyRegIdx <<
"\n");
1943 deleteInstr(CopyMI);
2031 const unsigned SubIdx;
2039 const bool SubRangeJoin;
2042 const bool TrackSubRegLiveness;
2057 enum ConflictResolution {
2088 ConflictResolution Resolution = CR_Keep;
2098 VNInfo *RedefVNI =
nullptr;
2101 VNInfo *OtherVNI =
nullptr;
2114 bool ErasableImplicitDef =
false;
2118 bool Pruned =
false;
2121 bool PrunedComputed =
false;
2128 bool Identical =
false;
2132 bool isAnalyzed()
const {
return WriteLanes.
any(); }
2144 std::pair<const VNInfo*,unsigned> followCopyChain(
const VNInfo *VNI)
const;
2146 bool valuesIdentical(
VNInfo *Value0,
VNInfo *Value1,
const JoinVals &
Other)
const;
2155 ConflictResolution analyzeValue(
unsigned ValNo, JoinVals &Other);
2160 void computeAssignment(
unsigned ValNo, JoinVals &Other);
2178 taintExtent(
unsigned ValNo,
LaneBitmask TaintedLanes, JoinVals &Other,
2191 bool isPrunedValue(
unsigned ValNo, JoinVals &Other);
2197 bool TrackSubRegLiveness)
2198 : LR(LR),
Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2199 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2205 bool mapValues(JoinVals &Other);
2209 bool resolveConflicts(JoinVals &Other);
2229 void pruneMainSegments(
LiveInterval &LI,
bool &ShrinkMainRange);
2240 void removeImplicitDefs();
2243 const int *getAssignments()
const {
return Assignments.
data(); }
2262 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
2263 const VNInfo *VNI)
const {
2264 unsigned TrackReg =
Reg;
2268 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2269 assert(MI &&
"No defining instruction");
2271 return std::make_pair(VNI, TrackReg);
2274 return std::make_pair(VNI, TrackReg);
2289 if ((SMask & LaneMask).none())
2297 return std::make_pair(VNI, TrackReg);
2300 if (ValueIn ==
nullptr) {
2307 return std::make_pair(
nullptr, SrcReg);
2312 return std::make_pair(VNI, TrackReg);
2315 bool JoinVals::valuesIdentical(
VNInfo *Value0,
VNInfo *Value1,
2316 const JoinVals &
Other)
const {
2319 std::tie(Orig0, Reg0) = followCopyChain(Value0);
2320 if (Orig0 == Value1 && Reg0 == Other.Reg)
2325 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
2329 if (Orig0 ==
nullptr || Orig1 ==
nullptr)
2330 return Orig0 == Orig1 && Reg0 == Reg1;
2336 return Orig0->
def == Orig1->
def && Reg0 == Reg1;
2339 JoinVals::ConflictResolution
2340 JoinVals::analyzeValue(
unsigned ValNo, JoinVals &Other) {
2341 Val &V = Vals[ValNo];
2342 assert(!V.isAnalyzed() &&
"Value has already been analyzed!");
2343 VNInfo *VNI = LR.getValNumInfo(ValNo);
2344 if (VNI->isUnused()) {
2351 if (VNI->isPHIDef()) {
2355 V.ValidLanes = V.WriteLanes = Lanes;
2357 DefMI = Indexes->getInstructionFromIndex(VNI->def);
2358 assert(DefMI !=
nullptr);
2364 V.ErasableImplicitDef =
true;
2368 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2386 V.RedefVNI = LR.Query(VNI->def).valueIn();
2387 assert((TrackSubRegLiveness || V.RedefVNI) &&
2388 "Instruction is reading nonexistent value");
2389 if (V.RedefVNI !=
nullptr) {
2390 computeAssignment(V.RedefVNI->id, Other);
2391 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2400 V.ErasableImplicitDef =
true;
2401 V.ValidLanes &= ~V.WriteLanes;
2418 if (OtherVNI->def < VNI->def)
2419 Other.computeAssignment(OtherVNI->id, *
this);
2420 else if (VNI->def < OtherVNI->def && OtherLRQ.
valueIn()) {
2423 V.OtherVNI = OtherLRQ.
valueIn();
2424 return CR_Impossible;
2426 V.OtherVNI = OtherVNI;
2427 Val &OtherV = Other.Vals[OtherVNI->id];
2429 if (!OtherV.isAnalyzed())
2434 if (VNI->isPHIDef())
2436 if ((V.ValidLanes & OtherV.ValidLanes).any())
2438 return CR_Impossible;
2444 V.OtherVNI = OtherLRQ.
valueIn();
2453 Other.computeAssignment(V.OtherVNI->id, *
this);
2454 Val &OtherV = Other.Vals[V.OtherVNI->id];
2463 if (OtherV.ErasableImplicitDef && DefMI &&
2464 DefMI->
getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
2465 LLVM_DEBUG(
dbgs() <<
"IMPLICIT_DEF defined at " << V.OtherVNI->def
2468 <<
", keeping it.\n");
2469 OtherV.ErasableImplicitDef =
false;
2474 if (VNI->isPHIDef())
2481 if (TrackSubRegLiveness
2482 && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)).none())
2492 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2507 valuesIdentical(VNI, V.OtherVNI, Other)) {
2524 if ((V.WriteLanes & OtherV.ValidLanes).none())
2536 assert(VNI->def.isEarlyClobber() &&
2537 "Only early clobber defs can overlap a kill");
2538 return CR_Impossible;
2546 return CR_Impossible;
2552 if (OtherLRQ.
endPoint() >= Indexes->getMBBEndIdx(MBB))
2553 return CR_Impossible;
2562 return CR_Unresolved;
2565 void JoinVals::computeAssignment(
unsigned ValNo, JoinVals &Other) {
2566 Val &V = Vals[ValNo];
2567 if (V.isAnalyzed()) {
2570 assert(Assignments[ValNo] != -1 &&
"Bad recursion?");
2573 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2577 assert(V.OtherVNI &&
"OtherVNI not assigned, can't merge.");
2578 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() &&
"Missing recursion");
2579 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2581 << LR.getValNumInfo(ValNo)->def <<
" into " 2582 <<
printReg(Other.Reg) <<
':' << V.OtherVNI->id <<
'@' 2583 << V.OtherVNI->def <<
" --> @" 2584 << NewVNInfo[Assignments[ValNo]]->def <<
'\n');
2587 case CR_Unresolved: {
2589 assert(V.OtherVNI &&
"OtherVNI not assigned, can't prune");
2590 Val &OtherV = Other.Vals[V.OtherVNI->id];
2593 if ((OtherV.WriteLanes & ~V.ValidLanes).any() && TrackSubRegLiveness)
2594 OtherV.ErasableImplicitDef =
false;
2595 OtherV.Pruned =
true;
2600 Assignments[ValNo] = NewVNInfo.size();
2601 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2606 bool JoinVals::mapValues(JoinVals &Other) {
2607 for (
unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2608 computeAssignment(i, Other);
2609 if (Vals[i].Resolution == CR_Impossible) {
2611 <<
'@' << LR.getValNumInfo(i)->def <<
'\n');
2619 taintExtent(
unsigned ValNo,
LaneBitmask TaintedLanes, JoinVals &Other,
2621 VNInfo *VNI = LR.getValNumInfo(ValNo);
2623 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2627 assert(OtherI != Other.LR.end() &&
"No conflict?");
2632 if (End >= MBBEnd) {
2634 << OtherI->valno->id <<
'@' << OtherI->start <<
'\n');
2638 << OtherI->valno->id <<
'@' << OtherI->start <<
" to " 2643 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2646 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2650 const Val &OV = Other.Vals[OtherI->valno->id];
2651 TaintedLanes &= ~OV.WriteLanes;
2654 }
while (TaintedLanes.
any());
2658 bool JoinVals::usesLanes(
const MachineInstr &MI,
unsigned Reg,
unsigned SubIdx,
2674 bool JoinVals::resolveConflicts(JoinVals &Other) {
2675 for (
unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2677 assert(V.Resolution != CR_Impossible &&
"Unresolvable conflict");
2678 if (V.Resolution != CR_Unresolved)
2681 << LR.getValNumInfo(i)->def <<
'\n');
2686 assert(V.OtherVNI &&
"Inconsistent conflict resolution.");
2687 VNInfo *VNI = LR.getValNumInfo(i);
2688 const Val &OtherV = Other.Vals[V.OtherVNI->id];
2693 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2695 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2699 assert(!TaintExtent.
empty() &&
"There should be at least one conflict.");
2705 MI = Indexes->getInstructionFromIndex(VNI->
def);
2710 "Interference ends on VNI->def. Should have been handled earlier");
2712 Indexes->getInstructionFromIndex(TaintExtent.
front().first);
2713 assert(LastMI &&
"Range must end at a proper instruction");
2714 unsigned TaintNum = 0;
2716 assert(MI != MBB->end() &&
"Bad LastMI");
2717 if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2722 if (&*MI == LastMI) {
2723 if (++TaintNum == TaintExtent.
size())
2725 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].
first);
2726 assert(LastMI &&
"Range must end at a proper instruction");
2727 TaintedLanes = TaintExtent[TaintNum].second;
2733 V.Resolution = CR_Replace;
2739 bool JoinVals::isPrunedValue(
unsigned ValNo, JoinVals &Other) {
2740 Val &V = Vals[ValNo];
2741 if (V.Pruned || V.PrunedComputed)
2744 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2749 V.PrunedComputed =
true;
2750 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *
this);
2754 void JoinVals::pruneValues(JoinVals &Other,
2756 bool changeInstrs) {
2757 for (
unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2759 switch (Vals[i].Resolution) {
2769 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2770 bool EraseImpDef = OtherV.ErasableImplicitDef &&
2771 OtherV.Resolution == CR_Keep;
2778 Indexes->getInstructionFromIndex(Def)->operands()) {
2792 <<
": " << Other.LR <<
'\n');
2797 if (isPrunedValue(i, Other)) {
2804 << Def <<
": " << LR <<
'\n');
2855 bool DidPrune =
false;
2856 for (
unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2860 if (V.Resolution != CR_Erase &&
2861 (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
2868 OtherDef = V.OtherVNI->def;
2871 LLVM_DEBUG(
dbgs() <<
"\t\tExpecting instruction removal at " << Def
2879 if (ValueOut !=
nullptr && Q.
valueIn() ==
nullptr) {
2881 <<
" at " << Def <<
"\n");
2888 if (V.Identical && S.Query(OtherDef).valueOut()) {
2902 ShrinkMask |= S.LaneMask;
2913 if (
VNInfo *VNI = SR.Query(Def).valueOutOrDead())
2914 if (VNI->
def == Def)
2920 void JoinVals::pruneMainSegments(
LiveInterval &LI,
bool &ShrinkMainRange) {
2921 assert(&static_cast<LiveRange&>(LI) == &LR);
2923 for (
unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2924 if (Vals[i].Resolution != CR_Keep)
2926 VNInfo *VNI = LR.getValNumInfo(i);
2929 Vals[i].Pruned =
true;
2930 ShrinkMainRange =
true;
2934 void JoinVals::removeImplicitDefs() {
2935 for (
unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2937 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
2940 VNInfo *VNI = LR.getValNumInfo(i);
2942 LR.removeValNo(VNI);
2949 for (
unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2952 switch (Vals[i].Resolution) {
2957 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2967 VNInfo *VNI = LR.getValNumInfo(i);
2971 if (LI !=
nullptr) {
2980 LR.removeValNo(VNI);
2986 assert(static_cast<LiveRange*>(LI) == &LR);
2996 ED = ED.
isValid() ? std::min(ED, I->start) : I->start;
3001 NewEnd = std::min(NewEnd, LE);
3003 NewEnd = std::min(NewEnd, ED);
3009 if (S != LR.begin())
3010 std::prev(S)->end = NewEnd;
3014 dbgs() <<
"\t\tremoved " << i <<
'@' << Def <<
": " << LR <<
'\n';
3016 dbgs() <<
"\t\t LHS = " << *LI <<
'\n';
3022 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
3023 assert(MI &&
"No instruction to erase");
3047 NewVNInfo,
CP, LIS,
TRI,
true,
true);
3048 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
3049 NewVNInfo,
CP, LIS,
TRI,
true,
true);
3056 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
3061 if (!LHSVals.resolveConflicts(RHSVals) ||
3062 !RHSVals.resolveConflicts(LHSVals)) {
3073 LHSVals.pruneValues(RHSVals, EndPoints,
false);
3074 RHSVals.pruneValues(LHSVals, EndPoints,
false);
3076 LHSVals.removeImplicitDefs();
3077 RHSVals.removeImplicitDefs();
3083 LRange.
join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
3087 <<
' ' << LRange <<
"\n");
3088 if (EndPoints.
empty())
3094 dbgs() <<
"\t\trestoring liveness to " << EndPoints.
size() <<
" points: ";
3095 for (
unsigned i = 0, n = EndPoints.
size(); i != n; ++i) {
3096 dbgs() << EndPoints[i];
3100 dbgs() <<
": " << LRange <<
'\n';
3102 LIS->extendToIndices(LRange, EndPoints);
3105 void RegisterCoalescer::mergeSubRangeInto(
LiveInterval &LI,
3113 SR.
assign(ToMerge, Allocator);
3116 LiveRange RangeCopy(ToMerge, Allocator);
3117 joinSubRegRanges(SR, RangeCopy, SR.
LaneMask, CP);
3128 NewVNInfo,
CP, LIS,
TRI,
false, TrackSubRegLiveness);
3130 NewVNInfo,
CP, LIS,
TRI,
false, TrackSubRegLiveness);
3132 LLVM_DEBUG(
dbgs() <<
"\t\tRHS = " << RHS <<
"\n\t\tLHS = " << LHS <<
'\n');
3136 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
3140 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
3149 unsigned DstIdx = CP.getDstIdx();
3152 : TRI->getSubRegIndexLaneMask(DstIdx);
3156 }
else if (DstIdx != 0) {
3159 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
3167 unsigned SrcIdx = CP.getSrcIdx();
3170 : TRI->getSubRegIndexLaneMask(SrcIdx);
3171 mergeSubRangeInto(LHS, RHS, Mask, CP);
3175 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3176 mergeSubRangeInto(LHS, R, Mask, CP);
3183 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3185 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
3186 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
3194 LHSVals.pruneValues(RHSVals, EndPoints,
true);
3195 RHSVals.pruneValues(LHSVals, EndPoints,
true);
3200 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3201 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3202 while (!ShrinkRegs.
empty())
3203 shrinkToUses(&LIS->getInterval(ShrinkRegs.
pop_back_val()));
3206 LHS.
join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3214 if (!EndPoints.
empty()) {
3218 dbgs() <<
"\t\trestoring liveness to " << EndPoints.
size() <<
" points: ";
3219 for (
unsigned i = 0, n = EndPoints.
size(); i != n; ++i) {
3220 dbgs() << EndPoints[i];
3224 dbgs() <<
": " << LHS <<
'\n';
3226 LIS->extendToIndices((
LiveRange&)LHS, EndPoints);
3233 return CP.
isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
3239 struct MBBPriorityInfo {
3245 : MBB(mbb),
Depth(depth), IsSplit(issplit) {}
3255 const MBBPriorityInfo *RHS) {
3257 if (LHS->Depth != RHS->Depth)
3258 return LHS->Depth > RHS->Depth ? -1 : 1;
3261 if (LHS->IsSplit != RHS->IsSplit)
3262 return LHS->IsSplit ? -1 : 1;
3266 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
3267 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
3269 return cl > cr ? -1 : 1;
3272 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
3293 bool RegisterCoalescer::
3295 bool Progress =
false;
3296 for (
unsigned i = 0, e = CurrList.
size(); i != e; ++i) {
3301 if (ErasedInstrs.
count(CurrList[i])) {
3302 CurrList[i] =
nullptr;
3306 bool Success = joinCopy(CurrList[i], Again);
3308 if (Success || !Again)
3309 CurrList[i] =
nullptr;
3326 bool RegisterCoalescer::applyTerminalRule(
const MachineInstr &Copy)
const {
3330 unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
3331 isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg);
3354 unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
3355 isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
3357 if (OtherReg == SrcReg)
3358 OtherReg = OtherSrcReg;
3379 const unsigned PrevSize = WorkList.
size();
3380 if (JoinGlobalCopies) {
3389 if (!MII->isCopyLike())
3391 bool ApplyTerminalRule = applyTerminalRule(*MII);
3393 if (ApplyTerminalRule)
3398 if (ApplyTerminalRule)
3405 LocalWorkList.
append(LocalTerminals.
begin(), LocalTerminals.
end());
3411 if (MII.isCopyLike()) {
3412 if (applyTerminalRule(MII))
3424 CurrList(WorkList.
begin() + PrevSize, WorkList.
end());
3425 if (copyCoalesceWorkList(CurrList))
3427 nullptr), WorkList.
end());
3430 void RegisterCoalescer::coalesceLocals() {
3431 copyCoalesceWorkList(LocalWorkList);
3432 for (
unsigned j = 0, je = LocalWorkList.
size(); j != je; ++j) {
3433 if (LocalWorkList[j])
3436 LocalWorkList.
clear();
3439 void RegisterCoalescer::joinAllIntervals() {
3440 LLVM_DEBUG(
dbgs() <<
"********** JOINING INTERVALS ***********\n");
3441 assert(WorkList.
empty() && LocalWorkList.
empty() &&
"Old data still around.");
3443 std::vector<MBBPriorityInfo> MBBs;
3444 MBBs.reserve(MF->
size());
3447 MBBs.push_back(MBBPriorityInfo(MBB, Loops->
getLoopDepth(MBB),
3454 for (
unsigned i = 0, e = MBBs.size(); i != e; ++i) {
3456 if (JoinGlobalCopies && MBBs[i].
Depth < CurrDepth) {
3458 CurrDepth = MBBs[i].Depth;
3460 copyCoalesceInMBB(MBBs[i].MBB);
3466 while (copyCoalesceWorkList(WorkList))
3470 void RegisterCoalescer::releaseMemory() {
3471 ErasedInstrs.
clear();
3474 InflateRegs.
clear();
3483 LIS = &getAnalysis<LiveIntervals>();
3484 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3485 Loops = &getAnalysis<MachineLoopInfo>();
3496 LLVM_DEBUG(
dbgs() <<
"********** SIMPLE REGISTER COALESCING **********\n" 3497 <<
"********** Function: " << MF->
getName() <<
'\n');
3500 MF->
verify(
this,
"Before register coalescing");
3512 InflateRegs.
erase(std::unique(InflateRegs.
begin(), InflateRegs.
end()),
3516 for (
unsigned i = 0, e = InflateRegs.
size(); i != e; ++i) {
3517 unsigned Reg = InflateRegs[i];
3537 assert((S.LaneMask & ~MaxMask).none());
3547 MF->
verify(
this,
"After register coalescing");
bool reg_nodbg_empty(unsigned RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions...
const TargetRegisterClass * getCommonSubClass(const TargetRegisterClass *A, const TargetRegisterClass *B, const MVT::SimpleValueType SVT=MVT::SimpleValueType::Any) const
Find the largest common subclass of A and B.
static bool isSplitEdge(const MachineBasicBlock *MBB)
Return true if this block should be vacated by the coalescer to eliminate branches.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
void push_back(const T &Elt)
iterator_range< reg_instr_nodbg_iterator > reg_nodbg_instructions(unsigned Reg) const
A common definition of LaneBitmask for use in TableGen and CodeGen.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
bool contains(unsigned Reg) const
Return true if the specified register is included in this register class.
virtual bool enableJoinGlobalCopies() const
True if the subtarget should enable joining global copies.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
SlotIndex def
The index of the defining instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
LaneBitmask getMaxLaneMaskForVReg(unsigned Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
Compute iterated dominance frontiers using a linear time algorithm.
bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const
Returns true if VNI is killed by any PHI-def values in LI.
void removePhysRegDefAt(unsigned Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
A Module instance is used to store all the information related to an LLVM module. ...
bool isCoalescable(const MachineInstr *) const
Return true if MI is a copy instruction that will become an identity copy after coalescing.
static cl::opt< bool > VerifyCoalescing("verify-coalescing", cl::desc("Verify machine instrs before and after register coalescing"), cl::Hidden)
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
Segments::iterator iterator
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator_range< use_nodbg_iterator > use_nodbg_operands(unsigned Reg) const
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Describe properties that are true of each instruction in the target description file.
unsigned getReg() const
getReg - Returns the register number.
void setIsUndef(bool Val=true)
void eliminateDeadDefs(SmallVectorImpl< MachineInstr *> &Dead, ArrayRef< unsigned > RegsBeingSpilled=None, AliasAnalysis *AA=nullptr)
eliminateDeadDefs - Try to delete machine instructions that are now dead (allDefsAreDead returns true...
static cl::opt< bool > EnableJoining("join-liveintervals", cl::desc("Coalesce copies (default=true)"), cl::init(true), cl::Hidden)
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(unsigned Reg) const
static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS)
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
unsigned getSubReg() const
bool test(unsigned Idx) const
static bool definesFullReg(const MachineInstr &MI, unsigned Reg)
Returns true if MI defines the full vreg Reg, as opposed to just defining a subregister.
iterator_range< reg_iterator > reg_operands(unsigned Reg) const
char & RegisterCoalescerID
RegisterCoalescer - This pass merges live ranges to eliminate copies.
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
unsigned getLoopDepth(const MachineBasicBlock *BB) const
Return the loop nesting level of the specified block.
A live range for subregisters.
bool isValid() const
Returns true if this is a valid index.
This represents a simple continuous liveness interval for a value.
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
void setIsDead(bool Val=true)
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
bool isPhys() const
Return true if DstReg is a physical register.
void markUnused()
Mark this value as unused.
void reserve(size_type N)
SubRange * createSubRangeFrom(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, const LiveRange &CopyFrom)
Like createSubRange() but the new range is filled with a copy of the liveness information in CopyFrom...
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
VNInfo - Value Number Information.
void print(raw_ostream &O, const Module *=nullptr) const override
Implement the dump method.
iterator_range< mop_iterator > operands()
void substVirtReg(unsigned Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool checkRegMaskInterference(LiveInterval &LI, BitVector &UsableRegs)
Test if LI is live across any register mask instructions, and compute a bit mask of physical register...
Callback methods for LiveRangeEdit owners.
void initializeRegisterCoalescerPass(PassRegistry &)
static MachineOperand CreateReg(unsigned Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
This class represents the liveness of a register, stack slot, etc.
static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def)
Check if any of the subranges of LI contain a definition at Def.
bool isUnused() const
Returns true if this value is unused.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
unsigned getDstReg() const
Return the register (virtual or physical) that will remain after coalescing.
bool isEarlyClobber() const
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
bool isPartial() const
Return true if the original copy instruction did not copy the full register, but was a subreg operati...
void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isBlock() const
isBlock - Returns true if this is a block boundary slot.
void pruneValue(LiveRange &LR, SlotIndex Kill, SmallVectorImpl< SlotIndex > *EndPoints)
If LR has a live value at Kill, prune its live range by removing any liveness reachable from Kill...
static use_iterator use_end()
void verify() const
Walk the range and assert if any invariants fail to hold.
virtual void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, unsigned SubIdx, const MachineInstr &Orig, const TargetRegisterInfo &TRI) const
Re-issue the specified 'original' instruction at the specific location targeting a new destination re...
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
const HexagonInstrInfo * TII
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
const TargetRegisterClass * getRegClass(const MCInstrDesc &MCID, unsigned OpNum, const TargetRegisterInfo *TRI, const MachineFunction &MF) const
Given a machine instruction descriptor, returns the register class constraint for OpNum...
Printable printReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
VNInfo::Allocator & getVNInfoAllocator()
A helper class for register coalescers.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator_range< subrange_iterator > subranges()
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Result of a LiveRange query.
static cl::opt< bool > EnableJoinSplits("join-splitedges", cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden)
Temporary flag to test critical edge unsplitting.
static constexpr LaneBitmask getAll()
bool hasSubRanges() const
Returns true if subregister liveness information is available.
static constexpr LaneBitmask getNone()
Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
static reg_instr_iterator reg_instr_end()
SlotIndex getNextNonNullIndex(SlotIndex Index)
Returns the next non-null index, if one exists.
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
defusechain_iterator - This class provides iterator support for machine operands in the function that...
void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
const TargetRegisterClass * getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA, const TargetRegisterClass *RCB, unsigned SubB, unsigned &PreA, unsigned &PreB) const
Find a common super-register class if it exists.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register. ...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
void clearKillFlags(unsigned Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
MCRegUnitRootIterator enumerates the root registers of a register unit.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
VNInfo * MergeValueNumberInto(VNInfo *V1, VNInfo *V2)
MergeValueNumberInto - This method is called when two value numbers are found to be equivalent...
AnalysisUsage & addPreservedID(const void *ID)
const char * getSubRegIndexName(unsigned SubIdx) const
Return the human-readable symbolic target-specific name for the specified SubRegIndex.
virtual const TargetInstrInfo * getInstrInfo() const
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
bool isKill() const
Return true if the live-in value is killed by this instruction.
bool setRegisters(const MachineInstr *)
Set registers to match the copy instruction MI.
VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc)
createDeadDef - Make sure the range has a value defined at Def.
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
bool allDefsAreDead() const
Return true if all the defs of this instruction are dead.
LiveRange * getCachedRegUnit(unsigned Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
static constexpr LaneBitmask getLane(unsigned Lane)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
bool containsOneValue() const
TargetInstrInfo - Interface to description of machine instruction set.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
static const unsigned CommuteAnyOperandIndex
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
SubRange * createSubRange(BumpPtrAllocator &Allocator, LaneBitmask LaneMask)
Creates a new empty subregister live range.
unsigned const MachineRegisterInfo * MRI
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
static int compareMBBPriority(const MBBPriorityInfo *LHS, const MBBPriorityInfo *RHS)
C-style comparator that sorts first based on the loop depth of the basic block (the unsigned)...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Allocate memory in an ever growing pool, as if by bump-pointer.
void removeInterval(unsigned Reg)
Interval removal.
bool liveAt(SlotIndex index) const
MachineInstrBuilder & UseMI
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src, const VNInfo *SrcValNo)
Copy segments with value number SrcValNo from liverange Src to live range and use value number DstVa...
void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval *> &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
unsigned composeSubRegIndices(unsigned a, unsigned b) const
Return the subregister index you get from composing two subregister indices.
SlotIndex getIndexBefore(const MachineInstr &MI) const
getIndexBefore - Returns the index of the last indexed instruction before MI, or the start index of i...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
unsigned getSubReg(unsigned Reg, unsigned Idx) const
Returns the physical register number of sub-register "Index" for physical register RegNo...
Represent the analysis usage information of a pass.
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr *> *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses...
void substPhysReg(unsigned Reg, const TargetRegisterInfo &)
substPhysReg - Substitute the current register with the physical register Reg, taking any existing Su...
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
virtual const TargetRegisterClass * getMatchingSuperRegClass(const TargetRegisterClass *A, const TargetRegisterClass *B, unsigned Idx) const
Return a subclass of the specified register class A so that each register in it has a sub-register of...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy, const MachineRegisterInfo *MRI)
Check if DstReg is a terminal node.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
constexpr bool all() const
void join(LiveRange &Other, const int *ValNoAssignments, const int *RHSValNoAssignments, SmallVectorImpl< VNInfo *> &NewVNInfo)
join - Join two live ranges (this, and other) together.
std::pair< bool, bool > readsWritesVirtualRegister(unsigned Reg, SmallVectorImpl< unsigned > *Ops=nullptr) const
Return a pair of bools (reads, writes) indicating if this instruction reads or writes Reg...
iterator_range< pred_iterator > predecessors()
void runOnMachineFunction(const MachineFunction &MF)
runOnFunction - Prepare to answer questions about MF.
bool isFlipped() const
Return true when getSrcReg is the register being defined by the original copy instruction.
void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, std::function< void(LiveInterval::SubRange &)> Apply)
Refines the subranges to support LaneMask.
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
unsigned getSrcReg() const
Return the virtual register that will be coalesced away.
virtual void updateRegAllocHint(unsigned Reg, unsigned NewReg, MachineFunction &MF) const
A callback to allow target a chance to update register allocation hints when a register is "changed" ...
bool isImplicitDef() const
iterator erase(const_iterator CI)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool isDebugInstr() const
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction, if any.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isConstantPhysReg(unsigned PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing", "Simple Register Coalescing", false, false) INITIALIZE_PASS_END(RegisterCoalescer
static cl::opt< cl::boolOrDefault > EnableGlobalCopies("join-globalcopies", cl::desc("Coalesce copies that span blocks (default=subtarget)"), cl::init(cl::BOU_UNSET), cl::Hidden)
Temporary flag to test global copy optimization.
unsigned getSrcIdx() const
Return the subregister index that SrcReg will be coalesced into, or 0.
void setIsKill(bool Val=true)
virtual bool isAsCheapAsAMove(const MachineInstr &MI) const
Return true if the instruction is as cheap as a move instruction.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
virtual bool shouldCoalesce(MachineInstr *MI, const TargetRegisterClass *SrcRC, unsigned SubReg, const TargetRegisterClass *DstRC, unsigned DstSubReg, const TargetRegisterClass *NewRC, LiveIntervals &LIS) const
Subtarget Hooks.
void setDesc(const MCInstrDesc &tid)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one...
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx, const TargetRegisterInfo &RegInfo)
Replace all occurrences of FromReg with ToReg:SubIdx, properly composing subreg indices where necessa...
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
unsigned getDstIdx() const
Return the subregister index that DstReg will be coalesced into, or 0.
iterator_range< use_iterator > use_operands(unsigned Reg) const
simple register coalescing
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
MachineInstrBuilder MachineInstrBuilder & DefMI
Promote Memory to Register
LLVM_NODISCARD T pop_back_val()
LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const
Return a bitmask representing the parts of a register that are covered by SubIdx. ...
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
LiveInterval & getInterval(unsigned Reg)
bool recomputeRegClass(unsigned Reg)
recomputeRegClass - Try to find a legal super-class of Reg's register class that still satisfies the ...
unsigned pred_size() const
virtual bool findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void clearSubRanges()
Removes all subregister liveness information.
LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA, LaneBitmask Mask) const
Transforms a LaneMask computed for one subregister to the lanemask that would have been computed when...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
void setDebugLoc(DebugLoc dl)
Replace current source information with new such.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
int findRegisterDefOperandIdx(unsigned Reg, bool isDead=false, bool Overlap=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a def of the specified register or -1 if it is not found...
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
bool readsRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
bool isUnconditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which always transfers control flow to some other block...
unsigned succ_size() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
const MachineBasicBlock * getParent() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
TargetSubtargetInfo - Generic base class for all target subtargets.
unsigned getNumValNums() const
Representation of each machine instruction.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static cl::opt< bool > UseTerminalRule("terminal-rule", cl::desc("Apply the terminal rule"), cl::init(false), cl::Hidden)
pointer data()
Return a pointer to the vector's buffer, even if empty().
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
use_iterator use_begin(unsigned RegNo) const
void assign(const LiveRange &Other, BumpPtrAllocator &Allocator)
Copies values numbers and live segments from Other into this range.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
bool isEHPad() const
Returns true if the block is a landing pad.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use...
LLVM_NODISCARD bool empty() const
unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx, const TargetRegisterClass *RC) const
Return a super-register of the specified register Reg so its sub-register of index SubIdx is Reg...
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
simple register Simple Register static false bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, unsigned &Src, unsigned &Dst, unsigned &SrcSub, unsigned &DstSub)
void setReg(unsigned Reg)
Change the register this operand corresponds to.
constexpr bool any() const
void setSubReg(unsigned subReg)
bool flip()
Swap SrcReg and DstReg.
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level...
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
SlotIndexes * getSlotIndexes() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const TargetRegisterClass * getNewRC() const
Return the register class of the coalesced register.
use_instr_nodbg_iterator use_instr_nodbg_begin(unsigned RegNo) const
simple register Simple Register Coalescing
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
This class implements an extremely fast bulk output stream that can only output to a stream...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
void setRegClass(unsigned Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
void RemoveOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with...
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none...
bool isValid() const
Check if the iterator is at the end of the list.
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const MachineOperand & getOperand(unsigned i) const
SlotIndex - An opaque wrapper around machine indexes.
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
bool isTriviallyReMaterializable(const MachineInstr &MI, AliasAnalysis *AA=nullptr) const
Return true if the instruction is trivially rematerializable, meaning it has no side effects and requ...
int findRegisterUseOperandIdx(unsigned Reg, bool isKill=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a use of the specific register or -1 if it is not found...
bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const
Return true if it is safe to move this instruction.
reg_instr_iterator reg_instr_begin(unsigned RegNo) const
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z, ..."), which produces the same result if Y and Z are exchanged.
LiveRange & getRegUnit(unsigned Unit)
Return the live range for register unit Unit.
bool isProperSubClass(const TargetRegisterClass *RC) const
isProperSubClass - Returns true if RC has a legal super-class with more allocatable registers...
bool isReserved(unsigned PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos)
Remove value number and related live segments of LI and its subranges that start at position Pos...