1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
40 STATISTIC(numJoins , "Number of interval joins performed");
41 STATISTIC(numCrossRCs , "Number of cross class joins performed");
42 STATISTIC(numCommutes , "Number of instruction commuting performed");
43 STATISTIC(numExtends , "Number of copies extended");
44 STATISTIC(NumReMats , "Number of instructions re-materialized");
45 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
46 STATISTIC(numAborts , "Number of times interval joining aborted");
47 STATISTIC(numDeadValNo, "Number of valno def marked dead");
49 char SimpleRegisterCoalescing::ID = 0;
51 EnableJoining("join-liveintervals",
52 cl::desc("Coalesce copies (default=true)"),
56 NewHeuristic("new-coalescer-heuristic",
57 cl::desc("Use new coalescer heuristic"),
58 cl::init(false), cl::Hidden);
61 DisableCrossClassJoin("disable-cross-class-join",
62 cl::desc("Avoid coalescing cross register class copies"),
63 cl::init(false), cl::Hidden);
66 PhysJoinTweak("tweak-phys-join-heuristics",
67 cl::desc("Tweak heuristics for joining phys reg with vr"),
68 cl::init(false), cl::Hidden);
70 static RegisterPass<SimpleRegisterCoalescing>
71 X("simple-register-coalescing", "Simple Register Coalescing");
73 // Declare that we implement the RegisterCoalescer interface
74 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
76 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
78 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
80 AU.addRequired<LiveIntervals>();
81 AU.addPreserved<LiveIntervals>();
82 AU.addRequired<MachineLoopInfo>();
83 AU.addPreserved<MachineLoopInfo>();
84 AU.addPreservedID(MachineDominatorsID);
86 AU.addPreservedID(StrongPHIEliminationID);
88 AU.addPreservedID(PHIEliminationID);
89 AU.addPreservedID(TwoAddressInstructionPassID);
90 MachineFunctionPass::getAnalysisUsage(AU);
93 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
94 /// being the source and IntB being the dest, thus this defines a value number
95 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
96 /// see if we can merge these two pieces of B into a single value number,
97 /// eliminating a copy. For example:
101 /// B1 = A3 <- this copy
103 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
104 /// value number to be replaced with B0 (which simplifies the B liveinterval).
106 /// This returns true if an interval was modified.
108 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
110 MachineInstr *CopyMI) {
111 MachineInstrIndex CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
113 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
114 // the example above.
115 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
116 assert(BLR != IntB.end() && "Live range not found!");
117 VNInfo *BValNo = BLR->valno;
119 // Get the location that B is defined at. Two options: either this value has
120 // an unknown definition point or it is defined at CopyIdx. If unknown, we
122 if (!BValNo->getCopy()) return false;
123 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
125 // AValNo is the value number in A that defines the copy, A3 in the example.
126 MachineInstrIndex CopyUseIdx = li_->getUseIndex(CopyIdx);
127 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
128 assert(ALR != IntA.end() && "Live range not found!");
129 VNInfo *AValNo = ALR->valno;
130 // If it's re-defined by an early clobber somewhere in the live range, then
131 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
133 // 172 %ECX<def> = MOV32rr %reg1039<kill>
134 // 180 INLINEASM <es:subl $5,$1
135 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
136 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
137 // 188 %EAX<def> = MOV32rr %EAX<kill>
138 // 196 %ECX<def> = MOV32rr %ECX<kill>
139 // 204 %ECX<def> = MOV32rr %ECX<kill>
140 // 212 %EAX<def> = MOV32rr %EAX<kill>
141 // 220 %EAX<def> = MOV32rr %EAX
142 // 228 %reg1039<def> = MOV32rr %ECX<kill>
143 // The early clobber operand ties ECX input to the ECX def.
145 // The live interval of ECX is represented as this:
146 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
147 // The coalescer has no idea there was a def in the middle of [174,230].
148 if (AValNo->hasRedefByEC())
151 // If AValNo is defined as a copy from IntB, we can potentially process this.
152 // Get the instruction that defines this value number.
153 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
154 if (!SrcReg) return false; // Not defined by a copy.
156 // If the value number is not defined by a copy instruction, ignore it.
158 // If the source register comes from an interval other than IntB, we can't
160 if (SrcReg != IntB.reg) return false;
162 // Get the LiveRange in IntB that this value number starts with.
163 LiveInterval::iterator ValLR =
164 IntB.FindLiveRangeContaining(li_->getPrevSlot(AValNo->def));
165 assert(ValLR != IntB.end() && "Live range not found!");
167 // Make sure that the end of the live range is inside the same block as
169 MachineInstr *ValLREndInst =
170 li_->getInstructionFromIndex(li_->getPrevSlot(ValLR->end));
172 ValLREndInst->getParent() != CopyMI->getParent()) return false;
174 // Okay, we now know that ValLR ends in the same block that the CopyMI
175 // live-range starts. If there are no intervening live ranges between them in
176 // IntB, we can merge them.
177 if (ValLR+1 != BLR) return false;
179 // If a live interval is a physical register, conservatively check if any
180 // of its sub-registers is overlapping the live interval of the virtual
181 // register. If so, do not coalesce.
182 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
183 *tri_->getSubRegisters(IntB.reg)) {
184 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
185 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
187 errs() << "Interfere with sub-register ";
188 li_->getInterval(*SR).print(errs(), tri_);
195 errs() << "\nExtending: ";
196 IntB.print(errs(), tri_);
199 MachineInstrIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
200 // We are about to delete CopyMI, so need to remove it as the 'instruction
201 // that defines this value #'. Update the the valnum with the new defining
203 BValNo->def = FillerStart;
206 // Okay, we can merge them. We need to insert a new liverange:
207 // [ValLR.end, BLR.begin) of either value number, then we merge the
208 // two value numbers.
209 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
211 // If the IntB live range is assigned to a physical register, and if that
212 // physreg has sub-registers, update their live intervals as well.
213 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
214 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
215 LiveInterval &SRLI = li_->getInterval(*SR);
216 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
217 SRLI.getNextValue(FillerStart, 0, true,
218 li_->getVNInfoAllocator())));
222 // Okay, merge "B1" into the same value number as "B0".
223 if (BValNo != ValLR->valno) {
224 IntB.addKills(ValLR->valno, BValNo->kills);
225 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
228 errs() << " result = ";
229 IntB.print(errs(), tri_);
233 // If the source instruction was killing the source register before the
234 // merge, unset the isKill marker given the live range has been extended.
235 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
237 ValLREndInst->getOperand(UIdx).setIsKill(false);
238 ValLR->valno->removeKill(FillerStart);
241 // If the copy instruction was killing the destination register before the
242 // merge, find the last use and trim the live range. That will also add the
244 if (CopyMI->killsRegister(IntA.reg))
245 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
251 /// HasOtherReachingDefs - Return true if there are definitions of IntB
252 /// other than BValNo val# that can reach uses of AValno val# of IntA.
253 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
257 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
259 if (AI->valno != AValNo) continue;
260 LiveInterval::Ranges::iterator BI =
261 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
262 if (BI != IntB.ranges.begin())
264 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
265 if (BI->valno == BValNo)
267 if (BI->start <= AI->start && BI->end > AI->start)
269 if (BI->start > AI->start && BI->start < AI->end)
276 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
277 /// being the source and IntB being the dest, thus this defines a value number
278 /// in IntB. If the source value number (in IntA) is defined by a commutable
279 /// instruction and its other operand is coalesced to the copy dest register,
280 /// see if we can transform the copy into a noop by commuting the definition. For
283 /// A3 = op A2 B0<kill>
285 /// B1 = A3 <- this copy
287 /// = op A3 <- more uses
291 /// B2 = op B0 A2<kill>
293 /// B1 = B2 <- now an identify copy
295 /// = op B2 <- more uses
297 /// This returns true if an interval was modified.
299 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
301 MachineInstr *CopyMI) {
302 MachineInstrIndex CopyIdx =
303 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
305 // FIXME: For now, only eliminate the copy by commuting its def when the
306 // source register is a virtual register. We want to guard against cases
307 // where the copy is a back edge copy and commuting the def lengthen the
308 // live interval of the source register to the entire loop.
309 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
312 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
313 // the example above.
314 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
315 assert(BLR != IntB.end() && "Live range not found!");
316 VNInfo *BValNo = BLR->valno;
318 // Get the location that B is defined at. Two options: either this value has
319 // an unknown definition point or it is defined at CopyIdx. If unknown, we
321 if (!BValNo->getCopy()) return false;
322 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
324 // AValNo is the value number in A that defines the copy, A3 in the example.
325 LiveInterval::iterator ALR =
326 IntA.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
328 assert(ALR != IntA.end() && "Live range not found!");
329 VNInfo *AValNo = ALR->valno;
330 // If other defs can reach uses of this def, then it's not safe to perform
331 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
333 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
334 AValNo->isUnused() || AValNo->hasPHIKill())
336 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
337 const TargetInstrDesc &TID = DefMI->getDesc();
338 if (!TID.isCommutable())
340 // If DefMI is a two-address instruction then commuting it will change the
341 // destination register.
342 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
343 assert(DefIdx != -1);
345 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
347 unsigned Op1, Op2, NewDstIdx;
348 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
352 else if (Op2 == UseOpIdx)
357 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
358 unsigned NewReg = NewDstMO.getReg();
359 if (NewReg != IntB.reg || !NewDstMO.isKill())
362 // Make sure there are no other definitions of IntB that would reach the
363 // uses which the new definition can reach.
364 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
367 // If some of the uses of IntA.reg is already coalesced away, return false.
368 // It's not possible to determine whether it's safe to perform the coalescing.
369 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
370 UE = mri_->use_end(); UI != UE; ++UI) {
371 MachineInstr *UseMI = &*UI;
372 MachineInstrIndex UseIdx = li_->getInstructionIndex(UseMI);
373 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
374 if (ULR == IntA.end())
376 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
380 // At this point we have decided that it is legal to do this
381 // transformation. Start by commuting the instruction.
382 MachineBasicBlock *MBB = DefMI->getParent();
383 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
386 if (NewMI != DefMI) {
387 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
388 MBB->insert(DefMI, NewMI);
391 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
392 NewMI->getOperand(OpIdx).setIsKill();
394 bool BHasPHIKill = BValNo->hasPHIKill();
395 SmallVector<VNInfo*, 4> BDeadValNos;
396 VNInfo::KillSet BKills;
397 std::map<MachineInstrIndex, MachineInstrIndex> BExtend;
399 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
408 // then do not add kills of A to the newly created B interval.
409 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
411 BExtend[ALR->end] = BLR->end;
413 // Update uses of IntA of the specific Val# with IntB.
414 bool BHasSubRegs = false;
415 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
416 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
417 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
418 UE = mri_->use_end(); UI != UE;) {
419 MachineOperand &UseMO = UI.getOperand();
420 MachineInstr *UseMI = &*UI;
422 if (JoinedCopies.count(UseMI))
424 MachineInstrIndex UseIdx = li_->getInstructionIndex(UseMI);
425 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
426 if (ULR == IntA.end() || ULR->valno != AValNo)
428 UseMO.setReg(NewReg);
431 if (UseMO.isKill()) {
433 UseMO.setIsKill(false);
435 BKills.push_back(li_->getNextSlot(li_->getUseIndex(UseIdx)));
437 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
438 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
440 if (DstReg == IntB.reg) {
441 // This copy will become a noop. If it's defining a new val#,
442 // remove that val# as well. However this live range is being
443 // extended to the end of the existing live range defined by the copy.
444 MachineInstrIndex DefIdx = li_->getDefIndex(UseIdx);
445 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
446 BHasPHIKill |= DLR->valno->hasPHIKill();
447 assert(DLR->valno->def == DefIdx);
448 BDeadValNos.push_back(DLR->valno);
449 BExtend[DLR->start] = DLR->end;
450 JoinedCopies.insert(UseMI);
451 // If this is a kill but it's going to be removed, the last use
452 // of the same val# is the new kill.
458 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
459 // simply extend BLR if CopyMI doesn't end the range.
461 errs() << "\nExtending: ";
462 IntB.print(errs(), tri_);
465 // Remove val#'s defined by copies that will be coalesced away.
466 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
467 VNInfo *DeadVNI = BDeadValNos[i];
469 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
470 LiveInterval &SRLI = li_->getInterval(*SR);
471 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
472 SRLI.removeValNo(SRLR->valno);
475 IntB.removeValNo(BDeadValNos[i]);
478 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
479 // is updated. Kills are also updated.
480 VNInfo *ValNo = BValNo;
481 ValNo->def = AValNo->def;
483 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
484 if (ValNo->kills[j] != BLR->end)
485 BKills.push_back(ValNo->kills[j]);
487 ValNo->kills.clear();
488 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
490 if (AI->valno != AValNo) continue;
491 MachineInstrIndex End = AI->end;
492 std::map<MachineInstrIndex, MachineInstrIndex>::iterator
493 EI = BExtend.find(End);
494 if (EI != BExtend.end())
496 IntB.addRange(LiveRange(AI->start, End, ValNo));
498 // If the IntB live range is assigned to a physical register, and if that
499 // physreg has sub-registers, update their live intervals as well.
501 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
502 LiveInterval &SRLI = li_->getInterval(*SR);
503 SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
507 IntB.addKills(ValNo, BKills);
508 ValNo->setHasPHIKill(BHasPHIKill);
511 errs() << " result = ";
512 IntB.print(errs(), tri_);
514 errs() << "\nShortening: ";
515 IntA.print(errs(), tri_);
518 IntA.removeValNo(AValNo);
521 errs() << " result = ";
522 IntA.print(errs(), tri_);
530 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
531 /// fallthoughs to SuccMBB.
532 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
533 MachineBasicBlock *SuccMBB,
534 const TargetInstrInfo *tii_) {
537 MachineBasicBlock *TBB = 0, *FBB = 0;
538 SmallVector<MachineOperand, 4> Cond;
539 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
540 MBB->isSuccessor(SuccMBB);
543 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
544 /// from a physical register live interval as well as from the live intervals
545 /// of its sub-registers.
546 static void removeRange(LiveInterval &li,
547 MachineInstrIndex Start, MachineInstrIndex End,
548 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
549 li.removeRange(Start, End, true);
550 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
551 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
552 if (!li_->hasInterval(*SR))
554 LiveInterval &sli = li_->getInterval(*SR);
555 MachineInstrIndex RemoveEnd = Start;
556 while (RemoveEnd != End) {
557 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
560 RemoveEnd = (LR->end < End) ? LR->end : End;
561 sli.removeRange(Start, RemoveEnd, true);
568 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
569 /// as the copy instruction, trim the live interval to the last use and return
572 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(MachineInstrIndex CopyIdx,
573 MachineBasicBlock *CopyMBB,
575 const LiveRange *LR) {
576 MachineInstrIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
577 MachineInstrIndex LastUseIdx;
578 MachineOperand *LastUse =
579 lastRegisterUse(LR->start, li_->getPrevSlot(CopyIdx), li.reg, LastUseIdx);
581 MachineInstr *LastUseMI = LastUse->getParent();
582 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
589 // r1025<dead> = r1024<kill>
590 if (MBBStart < LR->end)
591 removeRange(li, MBBStart, LR->end, li_, tri_);
595 // There are uses before the copy, just shorten the live range to the end
597 LastUse->setIsKill();
598 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
599 LR->valno->addKill(li_->getNextSlot(LastUseIdx));
600 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
601 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
603 // Last use is itself an identity code.
604 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
605 LastUseMI->getOperand(DeadIdx).setIsDead();
611 if (LR->start <= MBBStart && LR->end > MBBStart) {
612 if (LR->start == MachineInstrIndex()) {
613 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
614 // Live-in to the function but dead. Remove it from entry live-in set.
615 mf_->begin()->removeLiveIn(li.reg);
617 // FIXME: Shorten intervals in BBs that reaches this BB.
623 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
624 /// computation, replace the copy by rematerialize the definition.
625 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
628 MachineInstr *CopyMI) {
629 MachineInstrIndex CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
630 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
631 assert(SrcLR != SrcInt.end() && "Live range not found!");
632 VNInfo *ValNo = SrcLR->valno;
633 // If other defs can reach uses of this def, then it's not safe to perform
634 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
636 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
637 ValNo->isUnused() || ValNo->hasPHIKill())
639 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
640 const TargetInstrDesc &TID = DefMI->getDesc();
641 if (!TID.isAsCheapAsAMove())
643 if (!DefMI->getDesc().isRematerializable() ||
644 !tii_->isTriviallyReMaterializable(DefMI))
646 bool SawStore = false;
647 if (!DefMI->isSafeToMove(tii_, SawStore))
649 if (TID.getNumDefs() != 1)
651 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
652 // Make sure the copy destination register class fits the instruction
653 // definition register class. The mismatch can happen as a result of earlier
654 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
655 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
656 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
657 if (mri_->getRegClass(DstReg) != RC)
659 } else if (!RC->contains(DstReg))
663 MachineInstrIndex DefIdx = li_->getDefIndex(CopyIdx);
664 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
665 DLR->valno->setCopy(0);
666 // Don't forget to update sub-register intervals.
667 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
668 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
669 if (!li_->hasInterval(*SR))
671 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
672 if (DLR && DLR->valno->getCopy() == CopyMI)
673 DLR->valno->setCopy(0);
677 // If copy kills the source register, find the last use and propagate
679 bool checkForDeadDef = false;
680 MachineBasicBlock *MBB = CopyMI->getParent();
681 if (CopyMI->killsRegister(SrcInt.reg))
682 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
683 checkForDeadDef = true;
686 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
687 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI);
688 MachineInstr *NewMI = prior(MII);
690 if (checkForDeadDef) {
691 // PR4090 fix: Trim interval failed because there was no use of the
692 // source interval in this MBB. If the def is in this MBB too then we
693 // should mark it dead:
694 if (DefMI->getParent() == MBB) {
695 DefMI->addRegisterDead(SrcInt.reg, tri_);
696 SrcLR->end = li_->getNextSlot(SrcLR->start);
700 // CopyMI may have implicit operands, transfer them over to the newly
701 // rematerialized instruction. And update implicit def interval valnos.
702 for (unsigned i = CopyMI->getDesc().getNumOperands(),
703 e = CopyMI->getNumOperands(); i != e; ++i) {
704 MachineOperand &MO = CopyMI->getOperand(i);
705 if (MO.isReg() && MO.isImplicit())
706 NewMI->addOperand(MO);
707 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
708 unsigned Reg = MO.getReg();
709 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
710 if (DLR && DLR->valno->getCopy() == CopyMI)
711 DLR->valno->setCopy(0);
715 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
716 CopyMI->eraseFromParent();
717 ReMatCopies.insert(CopyMI);
718 ReMatDefs.insert(DefMI);
723 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
725 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
726 unsigned DstReg) const {
727 MachineBasicBlock *MBB = CopyMI->getParent();
728 const MachineLoop *L = loopInfo->getLoopFor(MBB);
731 if (MBB != L->getLoopLatch())
734 LiveInterval &LI = li_->getInterval(DstReg);
735 MachineInstrIndex DefIdx = li_->getInstructionIndex(CopyMI);
736 LiveInterval::const_iterator DstLR =
737 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
738 if (DstLR == LI.end())
740 if (DstLR->valno->kills.size() == 1 && DstLR->valno->kills[0].isPHIIndex())
745 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
746 /// update the subregister number if it is not zero. If DstReg is a
747 /// physical register and the existing subregister number of the def / use
748 /// being updated is not zero, make sure to set it to the correct physical
751 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
753 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
754 if (DstIsPhys && SubIdx) {
755 // Figure out the real physical register we are updating with.
756 DstReg = tri_->getSubReg(DstReg, SubIdx);
760 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
761 E = mri_->reg_end(); I != E; ) {
762 MachineOperand &O = I.getOperand();
763 MachineInstr *UseMI = &*I;
765 unsigned OldSubIdx = O.getSubReg();
767 unsigned UseDstReg = DstReg;
769 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
771 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
772 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
773 CopySrcSubIdx, CopyDstSubIdx) &&
774 CopySrcReg != CopyDstReg &&
775 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
776 // If the use is a copy and it won't be coalesced away, and its source
777 // is defined by a trivial computation, try to rematerialize it instead.
778 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
779 CopyDstSubIdx, UseMI))
788 // Sub-register indexes goes from small to large. e.g.
789 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
790 // EAX: 1 -> AL, 2 -> AX
791 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
792 // sub-register 2 is also AX.
793 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
794 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
797 // Remove would-be duplicated kill marker.
798 if (O.isKill() && UseMI->killsRegister(DstReg))
802 // After updating the operand, check if the machine instruction has
803 // become a copy. If so, update its val# information.
804 if (JoinedCopies.count(UseMI))
807 const TargetInstrDesc &TID = UseMI->getDesc();
808 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
809 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
810 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
811 CopySrcSubIdx, CopyDstSubIdx) &&
812 CopySrcReg != CopyDstReg &&
813 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
814 allocatableRegs_[CopyDstReg])) {
815 LiveInterval &LI = li_->getInterval(CopyDstReg);
816 MachineInstrIndex DefIdx =
817 li_->getDefIndex(li_->getInstructionIndex(UseMI));
818 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
819 if (DLR->valno->def == DefIdx)
820 DLR->valno->setCopy(UseMI);
826 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
827 /// due to live range lengthening as the result of coalescing.
828 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
830 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
831 UE = mri_->use_end(); UI != UE; ++UI) {
832 MachineOperand &UseMO = UI.getOperand();
835 MachineInstr *UseMI = UseMO.getParent();
836 MachineInstrIndex UseIdx =
837 li_->getUseIndex(li_->getInstructionIndex(UseMI));
838 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
839 if (!LR || !LR->valno->isKill(li_->getNextSlot(UseIdx))) {
840 if (LR->valno->def != li_->getNextSlot(UseIdx)) {
841 // Interesting problem. After coalescing reg1027's def and kill are both
842 // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814)
845 // 60 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
846 // 68 %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
847 // 76 t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
848 // 84 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
849 // 96 t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
851 // Do not remove the kill marker on t2LDRi12.
852 UseMO.setIsKill(false);
858 /// removeIntervalIfEmpty - Check if the live interval of a physical register
859 /// is empty, if so remove it and also remove the empty intervals of its
860 /// sub-registers. Return true if live interval is removed.
861 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
862 const TargetRegisterInfo *tri_) {
864 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
865 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
866 if (!li_->hasInterval(*SR))
868 LiveInterval &sli = li_->getInterval(*SR);
870 li_->removeInterval(*SR);
872 li_->removeInterval(li.reg);
878 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
879 /// Return true if live interval is removed.
880 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
881 MachineInstr *CopyMI) {
882 MachineInstrIndex CopyIdx = li_->getInstructionIndex(CopyMI);
883 LiveInterval::iterator MLR =
884 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
886 return false; // Already removed by ShortenDeadCopySrcLiveRange.
887 MachineInstrIndex RemoveStart = MLR->start;
888 MachineInstrIndex RemoveEnd = MLR->end;
889 MachineInstrIndex DefIdx = li_->getDefIndex(CopyIdx);
890 // Remove the liverange that's defined by this.
891 if (RemoveStart == DefIdx && RemoveEnd == li_->getNextSlot(DefIdx)) {
892 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
893 return removeIntervalIfEmpty(li, li_, tri_);
898 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
899 /// the val# it defines. If the live interval becomes empty, remove it as well.
900 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
901 MachineInstr *DefMI) {
902 MachineInstrIndex DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
903 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
904 if (DefIdx != MLR->valno->def)
906 li.removeValNo(MLR->valno);
907 return removeIntervalIfEmpty(li, li_, tri_);
910 /// PropagateDeadness - Propagate the dead marker to the instruction which
911 /// defines the val#.
912 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
913 MachineInstrIndex &LRStart, LiveIntervals *li_,
914 const TargetRegisterInfo* tri_) {
915 MachineInstr *DefMI =
916 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
917 if (DefMI && DefMI != CopyMI) {
918 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
920 DefMI->getOperand(DeadIdx).setIsDead();
922 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
923 true, true, false, true));
924 LRStart = li_->getNextSlot(LRStart);
928 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
929 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
930 /// ends the live range there. If there isn't another use, then this live range
931 /// is dead. Return true if live interval is removed.
933 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
934 MachineInstr *CopyMI) {
935 MachineInstrIndex CopyIdx = li_->getInstructionIndex(CopyMI);
936 if (CopyIdx == MachineInstrIndex()) {
937 // FIXME: special case: function live in. It can be a general case if the
938 // first instruction index starts at > 0 value.
939 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
940 // Live-in to the function but dead. Remove it from entry live-in set.
941 if (mf_->begin()->isLiveIn(li.reg))
942 mf_->begin()->removeLiveIn(li.reg);
943 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
944 removeRange(li, LR->start, LR->end, li_, tri_);
945 return removeIntervalIfEmpty(li, li_, tri_);
948 LiveInterval::iterator LR =
949 li.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
951 // Livein but defined by a phi.
954 MachineInstrIndex RemoveStart = LR->start;
955 MachineInstrIndex RemoveEnd = li_->getNextSlot(li_->getDefIndex(CopyIdx));
956 if (LR->end > RemoveEnd)
957 // More uses past this copy? Nothing to do.
960 // If there is a last use in the same bb, we can't remove the live range.
961 // Shorten the live interval and return.
962 MachineBasicBlock *CopyMBB = CopyMI->getParent();
963 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
966 // There are other kills of the val#. Nothing to do.
967 if (!li.isOnlyLROfValNo(LR))
970 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
971 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
972 // If the live range starts in another mbb and the copy mbb is not a fall
973 // through mbb, then we can only cut the range from the beginning of the
975 RemoveStart = li_->getNextSlot(li_->getMBBStartIdx(CopyMBB));
977 if (LR->valno->def == RemoveStart) {
978 // If the def MI defines the val# and this copy is the only kill of the
979 // val#, then propagate the dead marker.
980 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
983 if (LR->valno->isKill(RemoveEnd))
984 LR->valno->removeKill(RemoveEnd);
987 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
988 return removeIntervalIfEmpty(li, li_, tri_);
991 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
992 /// from an implicit def to another register can be coalesced away.
993 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
995 LiveInterval &ImpLi) const{
996 if (!CopyMI->killsRegister(ImpLi.reg))
998 // Make sure this is the only use.
999 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1000 UE = mri_->use_end(); UI != UE;) {
1001 MachineInstr *UseMI = &*UI;
1003 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1011 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1012 /// a virtual destination register with physical source register.
1014 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1015 MachineBasicBlock *CopyMBB,
1016 LiveInterval &DstInt,
1017 LiveInterval &SrcInt) {
1018 // If the virtual register live interval is long but it has low use desity,
1019 // do not join them, instead mark the physical register as its allocation
1021 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1022 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1023 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1024 if (Length > Threshold &&
1025 (((float)std::distance(mri_->use_begin(DstInt.reg),
1026 mri_->use_end()) / Length) < (1.0 / Threshold)))
1029 // If the virtual register live interval extends into a loop, turn down
1031 MachineInstrIndex CopyIdx =
1032 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1033 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1035 // Let's see if the virtual register live interval extends into the loop.
1036 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1037 assert(DLR != DstInt.end() && "Live range not found!");
1038 DLR = DstInt.FindLiveRangeContaining(li_->getNextSlot(DLR->end));
1039 if (DLR != DstInt.end()) {
1040 CopyMBB = li_->getMBBFromIndex(DLR->start);
1041 L = loopInfo->getLoopFor(CopyMBB);
1045 if (!L || Length <= Threshold)
1048 MachineInstrIndex UseIdx = li_->getUseIndex(CopyIdx);
1049 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1050 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1051 if (loopInfo->getLoopFor(SMBB) != L) {
1052 if (!loopInfo->isLoopHeader(CopyMBB))
1054 // If vr's live interval extends pass the loop header, do not join.
1055 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1056 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1057 MachineBasicBlock *SuccMBB = *SI;
1058 if (SuccMBB == CopyMBB)
1060 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1061 li_->getNextSlot(li_->getMBBEndIdx(SuccMBB))))
1068 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1069 /// copy from a virtual source register to a physical destination register.
1071 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1072 MachineBasicBlock *CopyMBB,
1073 LiveInterval &DstInt,
1074 LiveInterval &SrcInt) {
1075 // If the virtual register live interval is long but it has low use desity,
1076 // do not join them, instead mark the physical register as its allocation
1078 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1079 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1080 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1081 if (Length > Threshold &&
1082 (((float)std::distance(mri_->use_begin(SrcInt.reg),
1083 mri_->use_end()) / Length) < (1.0 / Threshold)))
1087 // Must be implicit_def.
1090 // If the virtual register live interval is defined or cross a loop, turn
1091 // down aggressiveness.
1092 MachineInstrIndex CopyIdx =
1093 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1094 MachineInstrIndex UseIdx = li_->getUseIndex(CopyIdx);
1095 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1096 assert(SLR != SrcInt.end() && "Live range not found!");
1097 SLR = SrcInt.FindLiveRangeContaining(li_->getPrevSlot(SLR->start));
1098 if (SLR == SrcInt.end())
1100 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1101 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1103 if (!L || Length <= Threshold)
1106 if (loopInfo->getLoopFor(CopyMBB) != L) {
1107 if (SMBB != L->getLoopLatch())
1109 // If vr's live interval is extended from before the loop latch, do not
1111 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1112 PE = SMBB->pred_end(); PI != PE; ++PI) {
1113 MachineBasicBlock *PredMBB = *PI;
1114 if (PredMBB == SMBB)
1116 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1117 li_->getNextSlot(li_->getMBBEndIdx(PredMBB))))
1124 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1125 /// two virtual registers from different register classes.
1127 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1129 unsigned Threshold) {
1130 // Then make sure the intervals are *short*.
1131 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1132 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1133 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1134 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1135 if (SmallSize > Threshold || LargeSize > Threshold)
1136 if ((float)std::distance(mri_->use_begin(SmallReg),
1137 mri_->use_end()) / SmallSize <
1138 (float)std::distance(mri_->use_begin(LargeReg),
1139 mri_->use_end()) / LargeSize)
1144 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1145 /// register with a physical register, check if any of the virtual register
1146 /// operand is a sub-register use or def. If so, make sure it won't result
1147 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1148 /// vr1024 = extract_subreg vr1025, 1
1150 /// vr1024 = mov8rr AH
1151 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1152 /// AH does not have a super-reg whose sub-register 1 is AH.
1154 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1157 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1158 E = mri_->reg_end(); I != E; ++I) {
1159 MachineOperand &O = I.getOperand();
1160 MachineInstr *MI = &*I;
1161 if (MI == CopyMI || JoinedCopies.count(MI))
1163 unsigned SubIdx = O.getSubReg();
1164 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1166 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1167 SubIdx = MI->getOperand(2).getImm();
1168 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1171 unsigned SrcReg = MI->getOperand(1).getReg();
1172 const TargetRegisterClass *RC =
1173 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1174 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1175 : mri_->getRegClass(SrcReg);
1176 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1180 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1181 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
1182 SubIdx = MI->getOperand(3).getImm();
1183 if (VirtReg == MI->getOperand(0).getReg()) {
1184 if (!tri_->getSubReg(PhysReg, SubIdx))
1187 unsigned DstReg = MI->getOperand(0).getReg();
1188 const TargetRegisterClass *RC =
1189 TargetRegisterInfo::isPhysicalRegister(DstReg)
1190 ? tri_->getPhysicalRegisterRegClass(DstReg)
1191 : mri_->getRegClass(DstReg);
1192 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1201 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1202 /// an extract_subreg where dst is a physical register, e.g.
1203 /// cl = EXTRACT_SUBREG reg1024, 1
1205 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1206 unsigned SrcReg, unsigned SubIdx,
1207 unsigned &RealDstReg) {
1208 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1209 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1210 assert(RealDstReg && "Invalid extract_subreg instruction!");
1212 // For this type of EXTRACT_SUBREG, conservatively
1213 // check if the live interval of the source register interfere with the
1214 // actual super physical register we are trying to coalesce with.
1215 LiveInterval &RHS = li_->getInterval(SrcReg);
1216 if (li_->hasInterval(RealDstReg) &&
1217 RHS.overlaps(li_->getInterval(RealDstReg))) {
1219 errs() << "Interfere with register ";
1220 li_->getInterval(RealDstReg).print(errs(), tri_);
1222 return false; // Not coalescable
1224 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1225 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1227 errs() << "Interfere with sub-register ";
1228 li_->getInterval(*SR).print(errs(), tri_);
1230 return false; // Not coalescable
1235 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1236 /// an insert_subreg where src is a physical register, e.g.
1237 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1239 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1240 unsigned SrcReg, unsigned SubIdx,
1241 unsigned &RealSrcReg) {
1242 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1243 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1244 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1246 LiveInterval &RHS = li_->getInterval(DstReg);
1247 if (li_->hasInterval(RealSrcReg) &&
1248 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1250 errs() << "Interfere with register ";
1251 li_->getInterval(RealSrcReg).print(errs(), tri_);
1253 return false; // Not coalescable
1255 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1256 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1258 errs() << "Interfere with sub-register ";
1259 li_->getInterval(*SR).print(errs(), tri_);
1261 return false; // Not coalescable
1266 /// getRegAllocPreference - Return register allocation preference register.
1268 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1269 MachineRegisterInfo *MRI,
1270 const TargetRegisterInfo *TRI) {
1271 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1273 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1274 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1277 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1278 /// which are the src/dst of the copy instruction CopyMI. This returns true
1279 /// if the copy was successfully coalesced away. If it is not currently
1280 /// possible to coalesce this interval, but it may be possible if other
1281 /// things get coalesced, then it returns true by reference in 'Again'.
1282 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1283 MachineInstr *CopyMI = TheCopy.MI;
1286 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1287 return false; // Already done.
1289 DEBUG(errs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1291 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1292 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1293 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1294 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
1295 unsigned SubIdx = 0;
1297 DstReg = CopyMI->getOperand(0).getReg();
1298 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1299 SrcReg = CopyMI->getOperand(1).getReg();
1300 SrcSubIdx = CopyMI->getOperand(2).getImm();
1301 } else if (isInsSubReg || isSubRegToReg) {
1302 DstReg = CopyMI->getOperand(0).getReg();
1303 DstSubIdx = CopyMI->getOperand(3).getImm();
1304 SrcReg = CopyMI->getOperand(2).getReg();
1305 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1306 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1307 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1308 // coalesced to a larger register so the subreg indices cancel out.
1309 DEBUG(errs() << "\tSource of insert_subreg is already coalesced "
1310 << "to another register.\n");
1311 return false; // Not coalescable.
1313 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1314 llvm_unreachable("Unrecognized copy instruction!");
1317 // If they are already joined we continue.
1318 if (SrcReg == DstReg) {
1319 DEBUG(errs() << "\tCopy already coalesced.\n");
1320 return false; // Not coalescable.
1323 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1324 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1326 // If they are both physical registers, we cannot join them.
1327 if (SrcIsPhys && DstIsPhys) {
1328 DEBUG(errs() << "\tCan not coalesce physregs.\n");
1329 return false; // Not coalescable.
1332 // We only join virtual registers with allocatable physical registers.
1333 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1334 DEBUG(errs() << "\tSrc reg is unallocatable physreg.\n");
1335 return false; // Not coalescable.
1337 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1338 DEBUG(errs() << "\tDst reg is unallocatable physreg.\n");
1339 return false; // Not coalescable.
1342 // Check that a physical source register is compatible with dst regclass
1344 unsigned SrcSubReg = SrcSubIdx ?
1345 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1346 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1347 const TargetRegisterClass *DstSubRC = DstRC;
1349 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1350 assert(DstSubRC && "Illegal subregister index");
1351 if (!DstSubRC->contains(SrcSubReg)) {
1352 DEBUG(errs() << "\tIncompatible destination regclass: "
1353 << tri_->getName(SrcSubReg) << " not in "
1354 << DstSubRC->getName() << ".\n");
1355 return false; // Not coalescable.
1359 // Check that a physical dst register is compatible with source regclass
1361 unsigned DstSubReg = DstSubIdx ?
1362 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1363 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1364 const TargetRegisterClass *SrcSubRC = SrcRC;
1366 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1367 assert(SrcSubRC && "Illegal subregister index");
1368 if (!SrcSubRC->contains(DstReg)) {
1369 DEBUG(errs() << "\tIncompatible source regclass: "
1370 << tri_->getName(DstSubReg) << " not in "
1371 << SrcSubRC->getName() << ".\n");
1373 return false; // Not coalescable.
1377 // Should be non-null only when coalescing to a sub-register class.
1378 bool CrossRC = false;
1379 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1380 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1381 const TargetRegisterClass *NewRC = NULL;
1382 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1383 unsigned RealDstReg = 0;
1384 unsigned RealSrcReg = 0;
1385 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1386 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1387 if (SrcIsPhys && isExtSubReg) {
1388 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1389 // coalesced with AX.
1390 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1392 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1393 // coalesced to a larger register so the subreg indices cancel out.
1394 if (DstSubIdx != SubIdx) {
1395 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1396 return false; // Not coalescable.
1399 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1401 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1402 // EAX = INSERT_SUBREG EAX, r1024, 0
1403 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1405 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1406 // coalesced to a larger register so the subreg indices cancel out.
1407 if (SrcSubIdx != SubIdx) {
1408 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1409 return false; // Not coalescable.
1412 DstReg = tri_->getSubReg(DstReg, SubIdx);
1414 } else if ((DstIsPhys && isExtSubReg) ||
1415 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1416 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1417 DEBUG(errs() << "\tSrc of extract_subreg already coalesced with reg"
1418 << " of a super-class.\n");
1419 return false; // Not coalescable.
1423 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1424 return false; // Not coalescable
1426 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1427 return false; // Not coalescable
1431 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1432 : CopyMI->getOperand(2).getSubReg();
1434 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1435 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1436 // coalesced to a larger register so the subreg indices cancel out.
1437 // Also check if the other larger register is of the same register
1438 // class as the would be resulting register.
1441 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1442 return false; // Not coalescable.
1446 if (!DstIsPhys && !SrcIsPhys) {
1447 if (isInsSubReg || isSubRegToReg) {
1448 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1449 } else // extract_subreg {
1450 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1453 DEBUG(errs() << "\t Conflicting sub-register indices.\n");
1454 return false; // Not coalescable
1457 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1458 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1459 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1460 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1461 Again = true; // May be possible to coalesce later.
1466 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1467 if (DisableCrossClassJoin)
1471 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1472 // with another? If it's the resulting destination register, then
1473 // the subidx must be propagated to uses (but only those defined
1474 // by the EXTRACT_SUBREG). If it's being coalesced into another
1475 // register, it should be safe because register is assumed to have
1476 // the register class of the super-register.
1478 // Process moves where one of the registers have a sub-register index.
1479 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1480 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1481 SubIdx = DstMO->getSubReg();
1483 if (SrcMO->getSubReg())
1484 // FIXME: can we handle this?
1486 // This is not an insert_subreg but it looks like one.
1487 // e.g. %reg1024:4 = MOV32rr %EAX
1490 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1491 return false; // Not coalescable
1495 SubIdx = SrcMO->getSubReg();
1497 // This is not a extract_subreg but it looks like one.
1498 // e.g. %cl = MOV16rr %reg1024:1
1501 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1502 return false; // Not coalescable
1508 unsigned LargeReg = SrcReg;
1509 unsigned SmallReg = DstReg;
1511 // Now determine the register class of the joined register.
1513 if (SubIdx && DstRC && DstRC->isASubClass()) {
1514 // This is a move to a sub-register class. However, the source is a
1515 // sub-register of a larger register class. We don't know what should
1516 // the register class be. FIXME.
1520 if (!DstIsPhys && !SrcIsPhys)
1522 } else if (!SrcIsPhys && !DstIsPhys) {
1523 NewRC = getCommonSubClass(SrcRC, DstRC);
1525 DEBUG(errs() << "\tDisjoint regclasses: "
1526 << SrcRC->getName() << ", "
1527 << DstRC->getName() << ".\n");
1528 return false; // Not coalescable.
1530 if (DstRC->getSize() > SrcRC->getSize())
1531 std::swap(LargeReg, SmallReg);
1534 // If we are joining two virtual registers and the resulting register
1535 // class is more restrictive (fewer register, smaller size). Check if it's
1536 // worth doing the merge.
1537 if (!SrcIsPhys && !DstIsPhys &&
1538 (isExtSubReg || DstRC->isASubClass()) &&
1539 !isWinToJoinCrossClass(LargeReg, SmallReg,
1540 allocatableRCRegs_[NewRC].count())) {
1541 DEBUG(errs() << "\tSrc/Dest are different register classes.\n");
1542 // Allow the coalescer to try again in case either side gets coalesced to
1543 // a physical register that's compatible with the other side. e.g.
1544 // r1024 = MOV32to32_ r1025
1545 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1546 Again = true; // May be possible to coalesce later.
1551 // Will it create illegal extract_subreg / insert_subreg?
1552 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1554 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1557 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1558 LiveInterval &DstInt = li_->getInterval(DstReg);
1559 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1560 "Register mapping is horribly broken!");
1563 errs() << "\t\tInspecting "; SrcInt.print(errs(), tri_);
1564 errs() << " and "; DstInt.print(errs(), tri_);
1568 // Save a copy of the virtual register live interval. We'll manually
1569 // merge this into the "real" physical register live interval this is
1571 LiveInterval *SavedLI = 0;
1573 SavedLI = li_->dupInterval(&SrcInt);
1574 else if (RealSrcReg)
1575 SavedLI = li_->dupInterval(&DstInt);
1577 // Check if it is necessary to propagate "isDead" property.
1578 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1579 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1580 bool isDead = mopd->isDead();
1582 // We need to be careful about coalescing a source physical register with a
1583 // virtual register. Once the coalescing is done, it cannot be broken and
1584 // these are not spillable! If the destination interval uses are far away,
1585 // think twice about coalescing them!
1586 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1587 // If the copy is in a loop, take care not to coalesce aggressively if the
1588 // src is coming in from outside the loop (or the dst is out of the loop).
1589 // If it's not in a loop, then determine whether to join them base purely
1590 // by the length of the interval.
1591 if (PhysJoinTweak) {
1593 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1594 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1596 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1597 Again = true; // May be possible to coalesce later.
1601 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1602 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1604 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1605 Again = true; // May be possible to coalesce later.
1610 // If the virtual register live interval is long but it has low use desity,
1611 // do not join them, instead mark the physical register as its allocation
1613 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1614 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1615 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1616 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1617 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1618 if (TheCopy.isBackEdge)
1619 Threshold *= 2; // Favors back edge copies.
1621 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1622 float Ratio = 1.0 / Threshold;
1623 if (Length > Threshold &&
1624 (((float)std::distance(mri_->use_begin(JoinVReg),
1625 mri_->use_end()) / Length) < Ratio)) {
1626 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1628 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1629 Again = true; // May be possible to coalesce later.
1636 // Okay, attempt to join these two intervals. On failure, this returns false.
1637 // Otherwise, if one of the intervals being joined is a physreg, this method
1638 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1639 // been modified, so we can use this information below to update aliases.
1640 bool Swapped = false;
1641 // If SrcInt is implicitly defined, it's safe to coalesce.
1642 bool isEmpty = SrcInt.empty();
1643 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1644 // Only coalesce an empty interval (defined by implicit_def) with
1645 // another interval which has a valno defined by the CopyMI and the CopyMI
1646 // is a kill of the implicit def.
1647 DEBUG(errs() << "Not profitable!\n");
1651 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1652 // Coalescing failed.
1654 // If definition of source is defined by trivial computation, try
1655 // rematerializing it.
1656 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1657 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1660 // If we can eliminate the copy without merging the live ranges, do so now.
1661 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1662 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1663 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1664 JoinedCopies.insert(CopyMI);
1668 // Otherwise, we are unable to join the intervals.
1669 DEBUG(errs() << "Interference!\n");
1670 Again = true; // May be possible to coalesce later.
1674 LiveInterval *ResSrcInt = &SrcInt;
1675 LiveInterval *ResDstInt = &DstInt;
1677 std::swap(SrcReg, DstReg);
1678 std::swap(ResSrcInt, ResDstInt);
1680 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1681 "LiveInterval::join didn't work right!");
1683 // If we're about to merge live ranges into a physical register live interval,
1684 // we have to update any aliased register's live ranges to indicate that they
1685 // have clobbered values for this range.
1686 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1687 // If this is a extract_subreg where dst is a physical register, e.g.
1688 // cl = EXTRACT_SUBREG reg1024, 1
1689 // then create and update the actual physical register allocated to RHS.
1690 if (RealDstReg || RealSrcReg) {
1691 LiveInterval &RealInt =
1692 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1693 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1694 E = SavedLI->vni_end(); I != E; ++I) {
1695 const VNInfo *ValNo = *I;
1696 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1697 false, // updated at *
1698 li_->getVNInfoAllocator());
1699 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1700 RealInt.addKills(NewValNo, ValNo->kills);
1701 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1703 RealInt.weight += SavedLI->weight;
1704 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1707 // Update the liveintervals of sub-registers.
1708 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1709 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1710 li_->getVNInfoAllocator());
1713 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1714 // larger super-register.
1715 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1716 !SrcIsPhys && !DstIsPhys) {
1717 if ((isExtSubReg && !Swapped) ||
1718 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1719 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1720 std::swap(SrcReg, DstReg);
1721 std::swap(ResSrcInt, ResDstInt);
1725 // Coalescing to a virtual register that is of a sub-register class of the
1726 // other. Make sure the resulting register is set to the right register class.
1730 // This may happen even if it's cross-rc coalescing. e.g.
1731 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1732 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1733 // be allocate a register from GR64_ABCD.
1735 mri_->setRegClass(DstReg, NewRC);
1738 // Add all copies that define val# in the source interval into the queue.
1739 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1740 e = ResSrcInt->vni_end(); i != e; ++i) {
1741 const VNInfo *vni = *i;
1742 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1743 if (vni->def == MachineInstrIndex() || vni->isUnused() || vni->isPHIDef() ||
1744 !vni->isDefAccurate())
1746 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1747 unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
1749 JoinedCopies.count(CopyMI) == 0 &&
1750 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1751 NewSrcSubIdx, NewDstSubIdx)) {
1752 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1753 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1754 isBackEdgeCopy(CopyMI, DstReg)));
1759 // Remember to delete the copy instruction.
1760 JoinedCopies.insert(CopyMI);
1762 // Some live range has been lengthened due to colaescing, eliminate the
1763 // unnecessary kills.
1764 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1765 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1766 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1768 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1770 // SrcReg is guarateed to be the register whose live interval that is
1772 li_->removeInterval(SrcReg);
1774 // Update regalloc hint.
1775 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1777 // Manually deleted the live interval copy.
1783 // If resulting interval has a preference that no longer fits because of subreg
1784 // coalescing, just clear the preference.
1785 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1786 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1787 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1788 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1789 if (!RC->contains(Preference))
1790 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1794 errs() << "\n\t\tJoined. Result = ";
1795 ResDstInt->print(errs(), tri_);
1803 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1804 /// compute what the resultant value numbers for each value in the input two
1805 /// ranges will be. This is complicated by copies between the two which can
1806 /// and will commonly cause multiple value numbers to be merged into one.
1808 /// VN is the value number that we're trying to resolve. InstDefiningValue
1809 /// keeps track of the new InstDefiningValue assignment for the result
1810 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1811 /// whether a value in this or other is a copy from the opposite set.
1812 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1813 /// already been assigned.
1815 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1816 /// contains the value number the copy is from.
1818 static unsigned ComputeUltimateVN(VNInfo *VNI,
1819 SmallVector<VNInfo*, 16> &NewVNInfo,
1820 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1821 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1822 SmallVector<int, 16> &ThisValNoAssignments,
1823 SmallVector<int, 16> &OtherValNoAssignments) {
1824 unsigned VN = VNI->id;
1826 // If the VN has already been computed, just return it.
1827 if (ThisValNoAssignments[VN] >= 0)
1828 return ThisValNoAssignments[VN];
1829 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1831 // If this val is not a copy from the other val, then it must be a new value
1832 // number in the destination.
1833 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1834 if (I == ThisFromOther.end()) {
1835 NewVNInfo.push_back(VNI);
1836 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1838 VNInfo *OtherValNo = I->second;
1840 // Otherwise, this *is* a copy from the RHS. If the other side has already
1841 // been computed, return it.
1842 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1843 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1845 // Mark this value number as currently being computed, then ask what the
1846 // ultimate value # of the other value is.
1847 ThisValNoAssignments[VN] = -2;
1848 unsigned UltimateVN =
1849 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1850 OtherValNoAssignments, ThisValNoAssignments);
1851 return ThisValNoAssignments[VN] = UltimateVN;
1854 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1855 return std::find(V.begin(), V.end(), Val) != V.end();
1858 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1859 /// the specified live interval is defined by a copy from the specified
1861 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1864 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1867 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1868 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1869 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1870 *tri_->getSuperRegisters(li.reg)) {
1871 // It's a sub-register live interval, we may not have precise information.
1873 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1874 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1876 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1877 DstReg == li.reg && SrcReg == Reg) {
1878 // Cache computed info.
1879 LR->valno->def = LR->start;
1880 LR->valno->setCopy(DefMI);
1887 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1888 /// caller of this method must guarantee that the RHS only contains a single
1889 /// value number and that the RHS is not defined by a copy from this
1890 /// interval. This returns false if the intervals are not joinable, or it
1891 /// joins them and returns true.
1892 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1893 assert(RHS.containsOneValue());
1895 // Some number (potentially more than one) value numbers in the current
1896 // interval may be defined as copies from the RHS. Scan the overlapping
1897 // portions of the LHS and RHS, keeping track of this and looking for
1898 // overlapping live ranges that are NOT defined as copies. If these exist, we
1901 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1902 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1904 if (LHSIt->start < RHSIt->start) {
1905 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1906 if (LHSIt != LHS.begin()) --LHSIt;
1907 } else if (RHSIt->start < LHSIt->start) {
1908 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1909 if (RHSIt != RHS.begin()) --RHSIt;
1912 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1915 // Determine if these live intervals overlap.
1916 bool Overlaps = false;
1917 if (LHSIt->start <= RHSIt->start)
1918 Overlaps = LHSIt->end > RHSIt->start;
1920 Overlaps = RHSIt->end > LHSIt->start;
1922 // If the live intervals overlap, there are two interesting cases: if the
1923 // LHS interval is defined by a copy from the RHS, it's ok and we record
1924 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1925 // coalesce these live ranges and we bail out.
1927 // If we haven't already recorded that this value # is safe, check it.
1928 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1929 // Copy from the RHS?
1930 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1931 return false; // Nope, bail out.
1933 if (LHSIt->contains(RHSIt->valno->def))
1934 // Here is an interesting situation:
1936 // vr1025 = copy vr1024
1941 // Even though vr1025 is copied from vr1024, it's not safe to
1942 // coalesce them since the live range of vr1025 intersects the
1943 // def of vr1024. This happens because vr1025 is assigned the
1944 // value of the previous iteration of vr1024.
1946 EliminatedLHSVals.push_back(LHSIt->valno);
1949 // We know this entire LHS live range is okay, so skip it now.
1950 if (++LHSIt == LHSEnd) break;
1954 if (LHSIt->end < RHSIt->end) {
1955 if (++LHSIt == LHSEnd) break;
1957 // One interesting case to check here. It's possible that we have
1958 // something like "X3 = Y" which defines a new value number in the LHS,
1959 // and is the last use of this liverange of the RHS. In this case, we
1960 // want to notice this copy (so that it gets coalesced away) even though
1961 // the live ranges don't actually overlap.
1962 if (LHSIt->start == RHSIt->end) {
1963 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1964 // We already know that this value number is going to be merged in
1965 // if coalescing succeeds. Just skip the liverange.
1966 if (++LHSIt == LHSEnd) break;
1968 // Otherwise, if this is a copy from the RHS, mark it as being merged
1970 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1971 if (LHSIt->contains(RHSIt->valno->def))
1972 // Here is an interesting situation:
1974 // vr1025 = copy vr1024
1979 // Even though vr1025 is copied from vr1024, it's not safe to
1980 // coalesced them since live range of vr1025 intersects the
1981 // def of vr1024. This happens because vr1025 is assigned the
1982 // value of the previous iteration of vr1024.
1984 EliminatedLHSVals.push_back(LHSIt->valno);
1986 // We know this entire LHS live range is okay, so skip it now.
1987 if (++LHSIt == LHSEnd) break;
1992 if (++RHSIt == RHSEnd) break;
1996 // If we got here, we know that the coalescing will be successful and that
1997 // the value numbers in EliminatedLHSVals will all be merged together. Since
1998 // the most common case is that EliminatedLHSVals has a single number, we
1999 // optimize for it: if there is more than one value, we merge them all into
2000 // the lowest numbered one, then handle the interval as if we were merging
2001 // with one value number.
2002 VNInfo *LHSValNo = NULL;
2003 if (EliminatedLHSVals.size() > 1) {
2004 // Loop through all the equal value numbers merging them into the smallest
2006 VNInfo *Smallest = EliminatedLHSVals[0];
2007 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
2008 if (EliminatedLHSVals[i]->id < Smallest->id) {
2009 // Merge the current notion of the smallest into the smaller one.
2010 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2011 Smallest = EliminatedLHSVals[i];
2013 // Merge into the smallest.
2014 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2017 LHSValNo = Smallest;
2018 } else if (EliminatedLHSVals.empty()) {
2019 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2020 *tri_->getSuperRegisters(LHS.reg))
2021 // Imprecise sub-register information. Can't handle it.
2023 llvm_unreachable("No copies from the RHS?");
2025 LHSValNo = EliminatedLHSVals[0];
2028 // Okay, now that there is a single LHS value number that we're merging the
2029 // RHS into, update the value number info for the LHS to indicate that the
2030 // value number is defined where the RHS value number was.
2031 const VNInfo *VNI = RHS.getValNumInfo(0);
2032 LHSValNo->def = VNI->def;
2033 LHSValNo->setCopy(VNI->getCopy());
2035 // Okay, the final step is to loop over the RHS live intervals, adding them to
2037 if (VNI->hasPHIKill())
2038 LHSValNo->setHasPHIKill(true);
2039 LHS.addKills(LHSValNo, VNI->kills);
2040 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2042 LHS.ComputeJoinedWeight(RHS);
2044 // Update regalloc hint if both are virtual registers.
2045 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2046 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2047 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2048 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2049 if (RHSPref != LHSPref)
2050 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2053 // Update the liveintervals of sub-registers.
2054 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2055 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2056 li_->getOrCreateInterval(*AS).MergeInClobberRanges(LHS,
2057 li_->getVNInfoAllocator());
2062 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2063 /// returns false. Otherwise, if one of the intervals being joined is a
2064 /// physreg, this method always canonicalizes LHS to be it. The output
2065 /// "RHS" will not have been modified, so we can use this information
2066 /// below to update aliases.
2068 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2070 // Compute the final value assignment, assuming that the live ranges can be
2072 SmallVector<int, 16> LHSValNoAssignments;
2073 SmallVector<int, 16> RHSValNoAssignments;
2074 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2075 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2076 SmallVector<VNInfo*, 16> NewVNInfo;
2078 // If a live interval is a physical register, conservatively check if any
2079 // of its sub-registers is overlapping the live interval of the virtual
2080 // register. If so, do not coalesce.
2081 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2082 *tri_->getSubRegisters(LHS.reg)) {
2083 // If it's coalescing a virtual register to a physical register, estimate
2084 // its live interval length. This is the *cost* of scanning an entire live
2085 // interval. If the cost is low, we'll do an exhaustive check instead.
2087 // If this is something like this:
2095 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2096 // less conservative check. It's possible a sub-register is defined before
2097 // v1024 (or live in) and live out of BB1.
2098 if (RHS.containsOneValue() &&
2099 li_->intervalIsInOneMBB(RHS) &&
2100 li_->getApproximateInstructionCount(RHS) <= 10) {
2101 // Perform a more exhaustive check for some common cases.
2102 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2105 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2106 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2108 errs() << "Interfere with sub-register ";
2109 li_->getInterval(*SR).print(errs(), tri_);
2114 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2115 *tri_->getSubRegisters(RHS.reg)) {
2116 if (LHS.containsOneValue() &&
2117 li_->getApproximateInstructionCount(LHS) <= 10) {
2118 // Perform a more exhaustive check for some common cases.
2119 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2122 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2123 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2125 errs() << "Interfere with sub-register ";
2126 li_->getInterval(*SR).print(errs(), tri_);
2133 // Compute ultimate value numbers for the LHS and RHS values.
2134 if (RHS.containsOneValue()) {
2135 // Copies from a liveinterval with a single value are simple to handle and
2136 // very common, handle the special case here. This is important, because
2137 // often RHS is small and LHS is large (e.g. a physreg).
2139 // Find out if the RHS is defined as a copy from some value in the LHS.
2140 int RHSVal0DefinedFromLHS = -1;
2142 VNInfo *RHSValNoInfo = NULL;
2143 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2144 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2145 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2146 // If RHS is not defined as a copy from the LHS, we can use simpler and
2147 // faster checks to see if the live ranges are coalescable. This joiner
2148 // can't swap the LHS/RHS intervals though.
2149 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2150 return SimpleJoin(LHS, RHS);
2152 RHSValNoInfo = RHSValNoInfo0;
2155 // It was defined as a copy from the LHS, find out what value # it is.
2157 LHS.getLiveRangeContaining(li_->getPrevSlot(RHSValNoInfo0->def))->valno;
2158 RHSValID = RHSValNoInfo->id;
2159 RHSVal0DefinedFromLHS = RHSValID;
2162 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2163 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2164 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2166 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2167 // should now get updated.
2168 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2171 unsigned VN = VNI->id;
2172 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2173 if (LHSSrcReg != RHS.reg) {
2174 // If this is not a copy from the RHS, its value number will be
2175 // unmodified by the coalescing.
2176 NewVNInfo[VN] = VNI;
2177 LHSValNoAssignments[VN] = VN;
2178 } else if (RHSValID == -1) {
2179 // Otherwise, it is a copy from the RHS, and we don't already have a
2180 // value# for it. Keep the current value number, but remember it.
2181 LHSValNoAssignments[VN] = RHSValID = VN;
2182 NewVNInfo[VN] = RHSValNoInfo;
2183 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2185 // Otherwise, use the specified value #.
2186 LHSValNoAssignments[VN] = RHSValID;
2187 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2188 NewVNInfo[VN] = RHSValNoInfo;
2189 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2193 NewVNInfo[VN] = VNI;
2194 LHSValNoAssignments[VN] = VN;
2198 assert(RHSValID != -1 && "Didn't find value #?");
2199 RHSValNoAssignments[0] = RHSValID;
2200 if (RHSVal0DefinedFromLHS != -1) {
2201 // This path doesn't go through ComputeUltimateVN so just set
2203 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2206 // Loop over the value numbers of the LHS, seeing if any are defined from
2208 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2211 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2214 // DstReg is known to be a register in the LHS interval. If the src is
2215 // from the RHS interval, we can use its value #.
2216 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2219 // Figure out the value # from the RHS.
2220 LHSValsDefinedFromRHS[VNI]=
2221 RHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2224 // Loop over the value numbers of the RHS, seeing if any are defined from
2226 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2229 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2232 // DstReg is known to be a register in the RHS interval. If the src is
2233 // from the LHS interval, we can use its value #.
2234 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2237 // Figure out the value # from the LHS.
2238 RHSValsDefinedFromLHS[VNI]=
2239 LHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2242 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2243 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2244 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2246 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2249 unsigned VN = VNI->id;
2250 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2252 ComputeUltimateVN(VNI, NewVNInfo,
2253 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2254 LHSValNoAssignments, RHSValNoAssignments);
2256 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2259 unsigned VN = VNI->id;
2260 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2262 // If this value number isn't a copy from the LHS, it's a new number.
2263 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2264 NewVNInfo.push_back(VNI);
2265 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2269 ComputeUltimateVN(VNI, NewVNInfo,
2270 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2271 RHSValNoAssignments, LHSValNoAssignments);
2275 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2276 // interval lists to see if these intervals are coalescable.
2277 LiveInterval::const_iterator I = LHS.begin();
2278 LiveInterval::const_iterator IE = LHS.end();
2279 LiveInterval::const_iterator J = RHS.begin();
2280 LiveInterval::const_iterator JE = RHS.end();
2282 // Skip ahead until the first place of potential sharing.
2283 if (I->start < J->start) {
2284 I = std::upper_bound(I, IE, J->start);
2285 if (I != LHS.begin()) --I;
2286 } else if (J->start < I->start) {
2287 J = std::upper_bound(J, JE, I->start);
2288 if (J != RHS.begin()) --J;
2292 // Determine if these two live ranges overlap.
2294 if (I->start < J->start) {
2295 Overlaps = I->end > J->start;
2297 Overlaps = J->end > I->start;
2300 // If so, check value # info to determine if they are really different.
2302 // If the live range overlap will map to the same value number in the
2303 // result liverange, we can still coalesce them. If not, we can't.
2304 if (LHSValNoAssignments[I->valno->id] !=
2305 RHSValNoAssignments[J->valno->id])
2309 if (I->end < J->end) {
2318 // Update kill info. Some live ranges are extended due to copy coalescing.
2319 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2320 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2321 VNInfo *VNI = I->first;
2322 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2323 NewVNInfo[LHSValID]->removeKill(VNI->def);
2324 if (VNI->hasPHIKill())
2325 NewVNInfo[LHSValID]->setHasPHIKill(true);
2326 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2329 // Update kill info. Some live ranges are extended due to copy coalescing.
2330 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2331 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2332 VNInfo *VNI = I->first;
2333 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2334 NewVNInfo[RHSValID]->removeKill(VNI->def);
2335 if (VNI->hasPHIKill())
2336 NewVNInfo[RHSValID]->setHasPHIKill(true);
2337 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2340 // If we get here, we know that we can coalesce the live ranges. Ask the
2341 // intervals to coalesce themselves now.
2342 if ((RHS.ranges.size() > LHS.ranges.size() &&
2343 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2344 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2345 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2349 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2357 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2358 // depth of the basic block (the unsigned), and then on the MBB number.
2359 struct DepthMBBCompare {
2360 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2361 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2362 if (LHS.first > RHS.first) return true; // Deeper loops first
2363 return LHS.first == RHS.first &&
2364 LHS.second->getNumber() < RHS.second->getNumber();
2369 /// getRepIntervalSize - Returns the size of the interval that represents the
2370 /// specified register.
2372 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2373 return Rc->getRepIntervalSize(Reg);
2376 /// CopyRecSort::operator - Join priority queue sorting function.
2378 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2379 // Inner loops first.
2380 if (left.LoopDepth > right.LoopDepth)
2382 else if (left.LoopDepth == right.LoopDepth)
2383 if (left.isBackEdge && !right.isBackEdge)
2388 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2389 std::vector<CopyRec> &TryAgain) {
2390 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
2392 std::vector<CopyRec> VirtCopies;
2393 std::vector<CopyRec> PhysCopies;
2394 std::vector<CopyRec> ImpDefCopies;
2395 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
2396 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2398 MachineInstr *Inst = MII++;
2400 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2401 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2402 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2403 DstReg = Inst->getOperand(0).getReg();
2404 SrcReg = Inst->getOperand(1).getReg();
2405 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2406 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
2407 DstReg = Inst->getOperand(0).getReg();
2408 SrcReg = Inst->getOperand(2).getReg();
2409 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2412 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2413 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2415 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
2417 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2418 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2419 else if (SrcIsPhys || DstIsPhys)
2420 PhysCopies.push_back(CopyRec(Inst, 0, false));
2422 VirtCopies.push_back(CopyRec(Inst, 0, false));
2429 // Try coalescing implicit copies first, followed by copies to / from
2430 // physical registers, then finally copies from virtual registers to
2431 // virtual registers.
2432 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2433 CopyRec &TheCopy = ImpDefCopies[i];
2435 if (!JoinCopy(TheCopy, Again))
2437 TryAgain.push_back(TheCopy);
2439 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2440 CopyRec &TheCopy = PhysCopies[i];
2442 if (!JoinCopy(TheCopy, Again))
2444 TryAgain.push_back(TheCopy);
2446 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2447 CopyRec &TheCopy = VirtCopies[i];
2449 if (!JoinCopy(TheCopy, Again))
2451 TryAgain.push_back(TheCopy);
2455 void SimpleRegisterCoalescing::joinIntervals() {
2456 DEBUG(errs() << "********** JOINING INTERVALS ***********\n");
2459 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2461 std::vector<CopyRec> TryAgainList;
2462 if (loopInfo->empty()) {
2463 // If there are no loops in the function, join intervals in function order.
2464 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2466 CopyCoalesceInMBB(I, TryAgainList);
2468 // Otherwise, join intervals in inner loops before other intervals.
2469 // Unfortunately we can't just iterate over loop hierarchy here because
2470 // there may be more MBB's than BB's. Collect MBB's for sorting.
2472 // Join intervals in the function prolog first. We want to join physical
2473 // registers with virtual registers before the intervals got too long.
2474 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2475 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2476 MachineBasicBlock *MBB = I;
2477 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2480 // Sort by loop depth.
2481 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2483 // Finally, join intervals in loop nest order.
2484 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2485 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2488 // Joining intervals can allow other intervals to be joined. Iteratively join
2489 // until we make no progress.
2491 SmallVector<CopyRec, 16> TryAgain;
2492 bool ProgressMade = true;
2493 while (ProgressMade) {
2494 ProgressMade = false;
2495 while (!JoinQueue->empty()) {
2496 CopyRec R = JoinQueue->pop();
2498 bool Success = JoinCopy(R, Again);
2500 ProgressMade = true;
2502 TryAgain.push_back(R);
2506 while (!TryAgain.empty()) {
2507 JoinQueue->push(TryAgain.back());
2508 TryAgain.pop_back();
2513 bool ProgressMade = true;
2514 while (ProgressMade) {
2515 ProgressMade = false;
2517 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2518 CopyRec &TheCopy = TryAgainList[i];
2521 bool Success = JoinCopy(TheCopy, Again);
2522 if (Success || !Again) {
2523 TheCopy.MI = 0; // Mark this one as done.
2524 ProgressMade = true;
2535 /// Return true if the two specified registers belong to different register
2536 /// classes. The registers may be either phys or virt regs.
2538 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2539 unsigned RegB) const {
2540 // Get the register classes for the first reg.
2541 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2542 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2543 "Shouldn't consider two physregs!");
2544 return !mri_->getRegClass(RegB)->contains(RegA);
2547 // Compare against the regclass for the second reg.
2548 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2549 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2550 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2551 return RegClassA != RegClassB;
2553 return !RegClassA->contains(RegB);
2556 /// lastRegisterUse - Returns the last use of the specific register between
2557 /// cycles Start and End or NULL if there are no uses.
2559 SimpleRegisterCoalescing::lastRegisterUse(MachineInstrIndex Start,
2560 MachineInstrIndex End,
2562 MachineInstrIndex &UseIdx) const{
2563 UseIdx = MachineInstrIndex();
2564 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2565 MachineOperand *LastUse = NULL;
2566 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2567 E = mri_->use_end(); I != E; ++I) {
2568 MachineOperand &Use = I.getOperand();
2569 MachineInstr *UseMI = Use.getParent();
2570 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2571 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2573 // Ignore identity copies.
2575 MachineInstrIndex Idx = li_->getInstructionIndex(UseMI);
2576 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2578 UseIdx = li_->getUseIndex(Idx);
2584 MachineInstrIndex s = Start;
2585 MachineInstrIndex e = li_->getBaseIndex(li_->getPrevSlot(End));
2587 // Skip deleted instructions
2588 MachineInstr *MI = li_->getInstructionFromIndex(e);
2589 while (e != MachineInstrIndex() && li_->getPrevIndex(e) >= s && !MI) {
2590 e = li_->getPrevIndex(e);
2591 MI = li_->getInstructionFromIndex(e);
2593 if (e < s || MI == NULL)
2596 // Ignore identity copies.
2597 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2598 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2600 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2601 MachineOperand &Use = MI->getOperand(i);
2602 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2603 tri_->regsOverlap(Use.getReg(), Reg)) {
2604 UseIdx = li_->getUseIndex(e);
2609 e = li_->getPrevIndex(e);
2616 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2617 if (TargetRegisterInfo::isPhysicalRegister(reg))
2618 errs() << tri_->getName(reg);
2620 errs() << "%reg" << reg;
2623 void SimpleRegisterCoalescing::releaseMemory() {
2624 JoinedCopies.clear();
2625 ReMatCopies.clear();
2629 bool SimpleRegisterCoalescing::isZeroLengthInterval(LiveInterval *li) const {
2630 for (LiveInterval::Ranges::const_iterator
2631 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2632 if (li_->getPrevIndex(i->end) > i->start)
2638 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2640 mri_ = &fn.getRegInfo();
2641 tm_ = &fn.getTarget();
2642 tri_ = tm_->getRegisterInfo();
2643 tii_ = tm_->getInstrInfo();
2644 li_ = &getAnalysis<LiveIntervals>();
2645 loopInfo = &getAnalysis<MachineLoopInfo>();
2647 DEBUG(errs() << "********** SIMPLE REGISTER COALESCING **********\n"
2648 << "********** Function: "
2649 << ((Value*)mf_->getFunction())->getName() << '\n');
2651 allocatableRegs_ = tri_->getAllocatableSet(fn);
2652 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2653 E = tri_->regclass_end(); I != E; ++I)
2654 allocatableRCRegs_.insert(std::make_pair(*I,
2655 tri_->getAllocatableSet(fn, *I)));
2657 // Join (coalesce) intervals if requested.
2658 if (EnableJoining) {
2661 errs() << "********** INTERVALS POST JOINING **********\n";
2662 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2663 I->second->print(errs(), tri_);
2669 // Perform a final pass over the instructions and compute spill weights
2670 // and remove identity moves.
2671 SmallVector<unsigned, 4> DeadDefs;
2672 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2673 mbbi != mbbe; ++mbbi) {
2674 MachineBasicBlock* mbb = mbbi;
2675 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2677 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2679 MachineInstr *MI = mii;
2680 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2681 if (JoinedCopies.count(MI)) {
2682 // Delete all coalesced copies.
2683 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2684 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2685 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2686 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
2687 "Unrecognized copy instruction");
2688 DstReg = MI->getOperand(0).getReg();
2690 if (MI->registerDefIsDead(DstReg)) {
2691 LiveInterval &li = li_->getInterval(DstReg);
2692 if (!ShortenDeadCopySrcLiveRange(li, MI))
2693 ShortenDeadCopyLiveRange(li, MI);
2695 li_->RemoveMachineInstrFromMaps(MI);
2696 mii = mbbi->erase(mii);
2701 // Now check if this is a remat'ed def instruction which is now dead.
2702 if (ReMatDefs.count(MI)) {
2704 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2705 const MachineOperand &MO = MI->getOperand(i);
2708 unsigned Reg = MO.getReg();
2711 if (TargetRegisterInfo::isVirtualRegister(Reg))
2712 DeadDefs.push_back(Reg);
2715 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2716 !mri_->use_empty(Reg)) {
2722 while (!DeadDefs.empty()) {
2723 unsigned DeadDef = DeadDefs.back();
2724 DeadDefs.pop_back();
2725 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2727 li_->RemoveMachineInstrFromMaps(mii);
2728 mii = mbbi->erase(mii);
2734 // If the move will be an identity move delete it
2735 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2736 if (isMove && SrcReg == DstReg) {
2737 if (li_->hasInterval(SrcReg)) {
2738 LiveInterval &RegInt = li_->getInterval(SrcReg);
2739 // If def of this move instruction is dead, remove its live range
2740 // from the dstination register's live interval.
2741 if (MI->registerDefIsDead(DstReg)) {
2742 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2743 ShortenDeadCopyLiveRange(RegInt, MI);
2746 li_->RemoveMachineInstrFromMaps(MI);
2747 mii = mbbi->erase(mii);
2750 SmallSet<unsigned, 4> UniqueUses;
2751 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2752 const MachineOperand &mop = MI->getOperand(i);
2753 if (mop.isReg() && mop.getReg() &&
2754 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2755 unsigned reg = mop.getReg();
2756 // Multiple uses of reg by the same instruction. It should not
2757 // contribute to spill weight again.
2758 if (UniqueUses.count(reg) != 0)
2760 LiveInterval &RegInt = li_->getInterval(reg);
2762 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2763 UniqueUses.insert(reg);
2771 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2772 LiveInterval &LI = *I->second;
2773 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2774 // If the live interval length is essentially zero, i.e. in every live
2775 // range the use follows def immediately, it doesn't make sense to spill
2776 // it and hope it will be easier to allocate for this li.
2777 if (isZeroLengthInterval(&LI))
2778 LI.weight = HUGE_VALF;
2780 bool isLoad = false;
2781 SmallVector<LiveInterval*, 4> SpillIs;
2782 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2783 // If all of the definitions of the interval are re-materializable,
2784 // it is a preferred candidate for spilling. If non of the defs are
2785 // loads, then it's potentially very cheap to re-materialize.
2786 // FIXME: this gets much more complicated once we support non-trivial
2787 // re-materialization.
2795 // Slightly prefer live interval that has been assigned a preferred reg.
2796 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2797 if (Hint.first || Hint.second)
2800 // Divide the weight of the interval by its size. This encourages
2801 // spilling of intervals that are large and have few uses, and
2802 // discourages spilling of small intervals with many uses.
2803 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2811 /// print - Implement the dump method.
2812 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2816 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2817 return new SimpleRegisterCoalescing();
2820 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2821 DEFINING_FILE_FOR(SimpleRegisterCoalescing)