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/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/OwningPtr.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
42 STATISTIC(numJoins , "Number of interval joins performed");
43 STATISTIC(numCrossRCs , "Number of cross class joins performed");
44 STATISTIC(numCommutes , "Number of instruction commuting performed");
45 STATISTIC(numExtends , "Number of copies extended");
46 STATISTIC(NumReMats , "Number of instructions re-materialized");
47 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
48 STATISTIC(numAborts , "Number of times interval joining aborted");
49 STATISTIC(numDeadValNo, "Number of valno def marked dead");
51 char SimpleRegisterCoalescing::ID = 0;
53 EnableJoining("join-liveintervals",
54 cl::desc("Coalesce copies (default=true)"),
58 DisableCrossClassJoin("disable-cross-class-join",
59 cl::desc("Avoid coalescing cross register class copies"),
60 cl::init(false), cl::Hidden);
62 INITIALIZE_AG_PASS(SimpleRegisterCoalescing, RegisterCoalescer,
63 "simple-register-coalescing", "Simple Register Coalescing",
66 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
68 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<AliasAnalysis>();
71 AU.addRequired<LiveIntervals>();
72 AU.addPreserved<LiveIntervals>();
73 AU.addPreserved<SlotIndexes>();
74 AU.addRequired<MachineLoopInfo>();
75 AU.addPreserved<MachineLoopInfo>();
76 AU.addPreservedID(MachineDominatorsID);
78 AU.addPreservedID(StrongPHIEliminationID);
80 AU.addPreservedID(PHIEliminationID);
81 AU.addPreservedID(TwoAddressInstructionPassID);
82 MachineFunctionPass::getAnalysisUsage(AU);
85 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
86 /// being the source and IntB being the dest, thus this defines a value number
87 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
88 /// see if we can merge these two pieces of B into a single value number,
89 /// eliminating a copy. For example:
93 /// B1 = A3 <- this copy
95 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
96 /// value number to be replaced with B0 (which simplifies the B liveinterval).
98 /// This returns true if an interval was modified.
100 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
101 MachineInstr *CopyMI) {
102 // Bail if there is no dst interval - can happen when merging physical subreg
104 if (!li_->hasInterval(CP.getDstReg()))
108 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
110 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
111 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
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 if (BLR == IntB.end()) return false;
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 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
127 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
128 // The live range might not exist after fun with physreg coalescing.
129 if (ALR == IntA.end()) return false;
130 VNInfo *AValNo = ALR->valno;
131 // If it's re-defined by an early clobber somewhere in the live range, then
132 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
134 // 172 %ECX<def> = MOV32rr %reg1039<kill>
135 // 180 INLINEASM <es:subl $5,$1
136 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
138 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
139 // 188 %EAX<def> = MOV32rr %EAX<kill>
140 // 196 %ECX<def> = MOV32rr %ECX<kill>
141 // 204 %ECX<def> = MOV32rr %ECX<kill>
142 // 212 %EAX<def> = MOV32rr %EAX<kill>
143 // 220 %EAX<def> = MOV32rr %EAX
144 // 228 %reg1039<def> = MOV32rr %ECX<kill>
145 // The early clobber operand ties ECX input to the ECX def.
147 // The live interval of ECX is represented as this:
148 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
149 // The coalescer has no idea there was a def in the middle of [174,230].
150 if (AValNo->hasRedefByEC())
153 // If AValNo is defined as a copy from IntB, we can potentially process this.
154 // Get the instruction that defines this value number.
155 if (!CP.isCoalescable(AValNo->getCopy()))
158 // Get the LiveRange in IntB that this value number starts with.
159 LiveInterval::iterator ValLR =
160 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
161 if (ValLR == IntB.end())
164 // Make sure that the end of the live range is inside the same block as
166 MachineInstr *ValLREndInst =
167 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
168 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
171 // Okay, we now know that ValLR ends in the same block that the CopyMI
172 // live-range starts. If there are no intervening live ranges between them in
173 // IntB, we can merge them.
174 if (ValLR+1 != BLR) return false;
176 // If a live interval is a physical register, conservatively check if any
177 // of its sub-registers is overlapping the live interval of the virtual
178 // register. If so, do not coalesce.
179 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
180 *tri_->getSubRegisters(IntB.reg)) {
181 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
182 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
184 dbgs() << "\t\tInterfere with sub-register ";
185 li_->getInterval(*SR).print(dbgs(), tri_);
192 dbgs() << "Extending: ";
193 IntB.print(dbgs(), tri_);
196 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
197 // We are about to delete CopyMI, so need to remove it as the 'instruction
198 // that defines this value #'. Update the valnum with the new defining
200 BValNo->def = FillerStart;
203 // Okay, we can merge them. We need to insert a new liverange:
204 // [ValLR.end, BLR.begin) of either value number, then we merge the
205 // two value numbers.
206 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
208 // If the IntB live range is assigned to a physical register, and if that
209 // physreg has sub-registers, update their live intervals as well.
210 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
211 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
212 if (!li_->hasInterval(*SR))
214 LiveInterval &SRLI = li_->getInterval(*SR);
215 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
216 SRLI.getNextValue(FillerStart, 0, true,
217 li_->getVNInfoAllocator())));
221 // Okay, merge "B1" into the same value number as "B0".
222 if (BValNo != ValLR->valno) {
223 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
226 dbgs() << " result = ";
227 IntB.print(dbgs(), tri_);
231 // If the source instruction was killing the source register before the
232 // merge, unset the isKill marker given the live range has been extended.
233 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
235 ValLREndInst->getOperand(UIdx).setIsKill(false);
238 // If the copy instruction was killing the destination register before the
239 // merge, find the last use and trim the live range. That will also add the
241 if (ALR->end == CopyIdx)
242 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
248 /// HasOtherReachingDefs - Return true if there are definitions of IntB
249 /// other than BValNo val# that can reach uses of AValno val# of IntA.
250 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
254 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
256 if (AI->valno != AValNo) continue;
257 LiveInterval::Ranges::iterator BI =
258 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
259 if (BI != IntB.ranges.begin())
261 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
262 if (BI->valno == BValNo)
264 // When BValNo is null, we're looking for a dummy clobber-value for a subreg.
265 if (!BValNo && !BI->valno->isDefAccurate() && !BI->valno->getCopy())
267 if (BI->start <= AI->start && BI->end > AI->start)
269 if (BI->start > AI->start && BI->start < AI->end)
277 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
278 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
280 MachineOperand &MO = MI->getOperand(i);
281 if (MO.isReg() && MO.isImplicit())
282 NewMI->addOperand(MO);
286 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
287 /// IntA being the source and IntB being the dest, thus this defines a value
288 /// number in IntB. If the source value number (in IntA) is defined by a
289 /// commutable instruction and its other operand is coalesced to the copy dest
290 /// register, see if we can transform the copy into a noop by commuting the
291 /// definition. For example,
293 /// A3 = op A2 B0<kill>
295 /// B1 = A3 <- this copy
297 /// = op A3 <- more uses
301 /// B2 = op B0 A2<kill>
303 /// B1 = B2 <- now an identify copy
305 /// = op B2 <- more uses
307 /// This returns true if an interval was modified.
309 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
310 MachineInstr *CopyMI) {
311 // FIXME: For now, only eliminate the copy by commuting its def when the
312 // source register is a virtual register. We want to guard against cases
313 // where the copy is a back edge copy and commuting the def lengthen the
314 // live interval of the source register to the entire loop.
315 if (CP.isPhys() && CP.isFlipped())
318 // Bail if there is no dst interval.
319 if (!li_->hasInterval(CP.getDstReg()))
323 li_->getInstructionIndex(CopyMI).getDefIndex();
326 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
328 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
330 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
331 // the example above.
332 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
333 if (BLR == IntB.end()) return false;
334 VNInfo *BValNo = BLR->valno;
336 // Get the location that B is defined at. Two options: either this value has
337 // an unknown definition point or it is defined at CopyIdx. If unknown, we
339 if (!BValNo->getCopy()) return false;
340 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
342 // AValNo is the value number in A that defines the copy, A3 in the example.
343 LiveInterval::iterator ALR =
344 IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); //
346 assert(ALR != IntA.end() && "Live range not found!");
347 VNInfo *AValNo = ALR->valno;
348 // If other defs can reach uses of this def, then it's not safe to perform
349 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
351 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
352 AValNo->isUnused() || AValNo->hasPHIKill())
354 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
357 const TargetInstrDesc &TID = DefMI->getDesc();
358 if (!TID.isCommutable())
360 // If DefMI is a two-address instruction then commuting it will change the
361 // destination register.
362 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
363 assert(DefIdx != -1);
365 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
367 unsigned Op1, Op2, NewDstIdx;
368 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
372 else if (Op2 == UseOpIdx)
377 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
378 unsigned NewReg = NewDstMO.getReg();
379 if (NewReg != IntB.reg || !NewDstMO.isKill())
382 // Make sure there are no other definitions of IntB that would reach the
383 // uses which the new definition can reach.
384 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
387 bool BHasSubRegs = false;
388 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
389 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
391 // Abort if the subregisters of IntB.reg have values that are not simply the
392 // clobbers from the superreg.
394 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
395 if (li_->hasInterval(*SR) &&
396 HasOtherReachingDefs(IntA, li_->getInterval(*SR), AValNo, 0))
399 // If some of the uses of IntA.reg is already coalesced away, return false.
400 // It's not possible to determine whether it's safe to perform the coalescing.
401 for (MachineRegisterInfo::use_nodbg_iterator UI =
402 mri_->use_nodbg_begin(IntA.reg),
403 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
404 MachineInstr *UseMI = &*UI;
405 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
406 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
407 if (ULR == IntA.end())
409 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
413 // At this point we have decided that it is legal to do this
414 // transformation. Start by commuting the instruction.
415 MachineBasicBlock *MBB = DefMI->getParent();
416 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
419 if (NewMI != DefMI) {
420 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
421 MBB->insert(DefMI, NewMI);
424 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
425 NewMI->getOperand(OpIdx).setIsKill();
427 bool BHasPHIKill = BValNo->hasPHIKill();
428 SmallVector<VNInfo*, 4> BDeadValNos;
429 std::map<SlotIndex, SlotIndex> BExtend;
431 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
439 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
441 BExtend[ALR->end] = BLR->end;
443 // Update uses of IntA of the specific Val# with IntB.
444 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
445 UE = mri_->use_end(); UI != UE;) {
446 MachineOperand &UseMO = UI.getOperand();
447 MachineInstr *UseMI = &*UI;
449 if (JoinedCopies.count(UseMI))
451 if (UseMI->isDebugValue()) {
452 // FIXME These don't have an instruction index. Not clear we have enough
453 // info to decide whether to do this replacement or not. For now do it.
454 UseMO.setReg(NewReg);
457 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
458 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
459 if (ULR == IntA.end() || ULR->valno != AValNo)
461 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
462 UseMO.substPhysReg(NewReg, *tri_);
464 UseMO.setReg(NewReg);
467 if (UseMO.isKill()) {
469 UseMO.setIsKill(false);
471 if (!UseMI->isCopy())
473 if (UseMI->getOperand(0).getReg() != IntB.reg ||
474 UseMI->getOperand(0).getSubReg())
477 // This copy will become a noop. If it's defining a new val#,
478 // remove that val# as well. However this live range is being
479 // extended to the end of the existing live range defined by the copy.
480 SlotIndex DefIdx = UseIdx.getDefIndex();
481 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
484 BHasPHIKill |= DLR->valno->hasPHIKill();
485 assert(DLR->valno->def == DefIdx);
486 BDeadValNos.push_back(DLR->valno);
487 BExtend[DLR->start] = DLR->end;
488 JoinedCopies.insert(UseMI);
491 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
492 // simply extend BLR if CopyMI doesn't end the range.
494 dbgs() << "Extending: ";
495 IntB.print(dbgs(), tri_);
498 // Remove val#'s defined by copies that will be coalesced away.
499 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
500 VNInfo *DeadVNI = BDeadValNos[i];
502 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
503 if (!li_->hasInterval(*SR))
505 LiveInterval &SRLI = li_->getInterval(*SR);
506 if (const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def))
507 SRLI.removeValNo(SRLR->valno);
510 IntB.removeValNo(BDeadValNos[i]);
513 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
515 VNInfo *ValNo = BValNo;
516 ValNo->def = AValNo->def;
518 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
520 if (AI->valno != AValNo) continue;
521 SlotIndex End = AI->end;
522 std::map<SlotIndex, SlotIndex>::iterator
523 EI = BExtend.find(End);
524 if (EI != BExtend.end())
526 IntB.addRange(LiveRange(AI->start, End, ValNo));
528 ValNo->setHasPHIKill(BHasPHIKill);
531 dbgs() << " result = ";
532 IntB.print(dbgs(), tri_);
533 dbgs() << "\nShortening: ";
534 IntA.print(dbgs(), tri_);
537 IntA.removeValNo(AValNo);
540 dbgs() << " result = ";
541 IntA.print(dbgs(), tri_);
549 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
550 /// fallthoughs to SuccMBB.
551 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
552 MachineBasicBlock *SuccMBB,
553 const TargetInstrInfo *tii_) {
556 MachineBasicBlock *TBB = 0, *FBB = 0;
557 SmallVector<MachineOperand, 4> Cond;
558 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
559 MBB->isSuccessor(SuccMBB);
562 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
563 /// from a physical register live interval as well as from the live intervals
564 /// of its sub-registers.
565 static void removeRange(LiveInterval &li,
566 SlotIndex Start, SlotIndex End,
567 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
568 li.removeRange(Start, End, true);
569 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
570 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
571 if (!li_->hasInterval(*SR))
573 LiveInterval &sli = li_->getInterval(*SR);
574 SlotIndex RemoveStart = Start;
575 SlotIndex RemoveEnd = Start;
577 while (RemoveEnd != End) {
578 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
581 RemoveEnd = (LR->end < End) ? LR->end : End;
582 sli.removeRange(RemoveStart, RemoveEnd, true);
583 RemoveStart = RemoveEnd;
589 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
590 /// as the copy instruction, trim the live interval to the last use and return
593 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
594 MachineBasicBlock *CopyMBB,
596 const LiveRange *LR) {
597 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
598 SlotIndex LastUseIdx;
599 MachineOperand *LastUse =
600 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
602 MachineInstr *LastUseMI = LastUse->getParent();
603 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
610 // r1025<dead> = r1024<kill>
611 if (MBBStart < LR->end)
612 removeRange(li, MBBStart, LR->end, li_, tri_);
616 // There are uses before the copy, just shorten the live range to the end
618 LastUse->setIsKill();
619 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
620 if (LastUseMI->isCopy()) {
621 MachineOperand &DefMO = LastUseMI->getOperand(0);
622 if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
629 if (LR->start <= MBBStart && LR->end > MBBStart) {
630 if (LR->start == li_->getZeroIndex()) {
631 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
632 // Live-in to the function but dead. Remove it from entry live-in set.
633 mf_->begin()->removeLiveIn(li.reg);
635 // FIXME: Shorten intervals in BBs that reaches this BB.
641 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
642 /// computation, replace the copy by rematerialize the definition.
643 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
646 MachineInstr *CopyMI) {
647 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
648 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
649 assert(SrcLR != SrcInt.end() && "Live range not found!");
650 VNInfo *ValNo = SrcLR->valno;
651 // If other defs can reach uses of this def, then it's not safe to perform
652 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
654 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
655 ValNo->isUnused() || ValNo->hasPHIKill())
657 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
658 assert(DefMI && "Defining instruction disappeared");
659 const TargetInstrDesc &TID = DefMI->getDesc();
660 if (!TID.isAsCheapAsAMove())
662 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
664 bool SawStore = false;
665 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
667 if (TID.getNumDefs() != 1)
669 if (!DefMI->isImplicitDef()) {
670 // Make sure the copy destination register class fits the instruction
671 // definition register class. The mismatch can happen as a result of earlier
672 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
673 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
674 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
675 if (mri_->getRegClass(DstReg) != RC)
677 } else if (!RC->contains(DstReg))
681 // If destination register has a sub-register index on it, make sure it mtches
682 // the instruction register class.
684 const TargetInstrDesc &TID = DefMI->getDesc();
685 if (TID.getNumDefs() != 1)
687 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
688 const TargetRegisterClass *DstSubRC =
689 DstRC->getSubRegisterRegClass(DstSubIdx);
690 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
693 else if (DefRC != DstSubRC)
697 RemoveCopyFlag(DstReg, CopyMI);
699 // If copy kills the source register, find the last use and propagate
701 bool checkForDeadDef = false;
702 MachineBasicBlock *MBB = CopyMI->getParent();
703 if (SrcLR->end == CopyIdx.getDefIndex())
704 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
705 checkForDeadDef = true;
708 MachineBasicBlock::iterator MII =
709 llvm::next(MachineBasicBlock::iterator(CopyMI));
710 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
711 MachineInstr *NewMI = prior(MII);
713 if (checkForDeadDef) {
714 // PR4090 fix: Trim interval failed because there was no use of the
715 // source interval in this MBB. If the def is in this MBB too then we
716 // should mark it dead:
717 if (DefMI->getParent() == MBB) {
718 DefMI->addRegisterDead(SrcInt.reg, tri_);
719 SrcLR->end = SrcLR->start.getNextSlot();
723 // CopyMI may have implicit operands, transfer them over to the newly
724 // rematerialized instruction. And update implicit def interval valnos.
725 for (unsigned i = CopyMI->getDesc().getNumOperands(),
726 e = CopyMI->getNumOperands(); i != e; ++i) {
727 MachineOperand &MO = CopyMI->getOperand(i);
728 if (MO.isReg() && MO.isImplicit())
729 NewMI->addOperand(MO);
731 RemoveCopyFlag(MO.getReg(), CopyMI);
734 TransferImplicitOps(CopyMI, NewMI);
735 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
736 CopyMI->eraseFromParent();
737 ReMatCopies.insert(CopyMI);
738 ReMatDefs.insert(DefMI);
739 DEBUG(dbgs() << "Remat: " << *NewMI);
744 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
745 /// update the subregister number if it is not zero. If DstReg is a
746 /// physical register and the existing subregister number of the def / use
747 /// being updated is not zero, make sure to set it to the correct physical
750 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
751 bool DstIsPhys = CP.isPhys();
752 unsigned SrcReg = CP.getSrcReg();
753 unsigned DstReg = CP.getDstReg();
754 unsigned SubIdx = CP.getSubIdx();
756 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
757 MachineInstr *UseMI = I.skipInstruction();) {
758 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
761 if (UseMI->isCopy() &&
762 !UseMI->getOperand(1).getSubReg() &&
763 !UseMI->getOperand(0).getSubReg() &&
764 UseMI->getOperand(1).getReg() == SrcReg &&
765 UseMI->getOperand(0).getReg() != SrcReg &&
766 UseMI->getOperand(0).getReg() != DstReg &&
767 !JoinedCopies.count(UseMI) &&
768 ReMaterializeTrivialDef(li_->getInterval(SrcReg),
769 UseMI->getOperand(0).getReg(), 0, UseMI))
773 SmallVector<unsigned,8> Ops;
775 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
776 bool Kills = false, Deads = false;
778 // Replace SrcReg with DstReg in all UseMI operands.
779 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
780 MachineOperand &MO = UseMI->getOperand(Ops[i]);
781 Kills |= MO.isKill();
782 Deads |= MO.isDead();
785 MO.substPhysReg(DstReg, *tri_);
787 MO.substVirtReg(DstReg, SubIdx, *tri_);
790 // This instruction is a copy that will be removed.
791 if (JoinedCopies.count(UseMI))
795 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
796 // read-modify-write of DstReg.
798 UseMI->addRegisterDead(DstReg, tri_);
799 else if (!Reads && Writes)
800 UseMI->addRegisterDefined(DstReg, tri_);
802 // Kill flags apply to the whole physical register.
803 if (DstIsPhys && Kills)
804 UseMI->addRegisterKilled(DstReg, tri_);
808 dbgs() << "\t\tupdated: ";
809 if (!UseMI->isDebugValue())
810 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
816 /// removeIntervalIfEmpty - Check if the live interval of a physical register
817 /// is empty, if so remove it and also remove the empty intervals of its
818 /// sub-registers. Return true if live interval is removed.
819 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
820 const TargetRegisterInfo *tri_) {
822 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
823 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
824 if (!li_->hasInterval(*SR))
826 LiveInterval &sli = li_->getInterval(*SR);
828 li_->removeInterval(*SR);
830 li_->removeInterval(li.reg);
836 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
837 /// Return true if live interval is removed.
838 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
839 MachineInstr *CopyMI) {
840 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
841 LiveInterval::iterator MLR =
842 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
844 return false; // Already removed by ShortenDeadCopySrcLiveRange.
845 SlotIndex RemoveStart = MLR->start;
846 SlotIndex RemoveEnd = MLR->end;
847 SlotIndex DefIdx = CopyIdx.getDefIndex();
848 // Remove the liverange that's defined by this.
849 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
850 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
851 return removeIntervalIfEmpty(li, li_, tri_);
856 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
857 /// the val# it defines. If the live interval becomes empty, remove it as well.
858 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
859 MachineInstr *DefMI) {
860 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
861 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
862 if (DefIdx != MLR->valno->def)
864 li.removeValNo(MLR->valno);
865 return removeIntervalIfEmpty(li, li_, tri_);
868 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
869 const MachineInstr *CopyMI) {
870 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
871 if (li_->hasInterval(DstReg)) {
872 LiveInterval &LI = li_->getInterval(DstReg);
873 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
874 if (LR->valno->getCopy() == CopyMI)
875 LR->valno->setCopy(0);
877 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
879 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
880 if (!li_->hasInterval(*AS))
882 LiveInterval &LI = li_->getInterval(*AS);
883 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
884 if (LR->valno->getCopy() == CopyMI)
885 LR->valno->setCopy(0);
889 /// PropagateDeadness - Propagate the dead marker to the instruction which
890 /// defines the val#.
891 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
892 SlotIndex &LRStart, LiveIntervals *li_,
893 const TargetRegisterInfo* tri_) {
894 MachineInstr *DefMI =
895 li_->getInstructionFromIndex(LRStart.getDefIndex());
896 if (DefMI && DefMI != CopyMI) {
897 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
899 DefMI->getOperand(DeadIdx).setIsDead();
901 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
902 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
903 LRStart = LRStart.getNextSlot();
907 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
908 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
909 /// ends the live range there. If there isn't another use, then this live range
910 /// is dead. Return true if live interval is removed.
912 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
913 MachineInstr *CopyMI) {
914 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
915 if (CopyIdx == SlotIndex()) {
916 // FIXME: special case: function live in. It can be a general case if the
917 // first instruction index starts at > 0 value.
918 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
919 // Live-in to the function but dead. Remove it from entry live-in set.
920 if (mf_->begin()->isLiveIn(li.reg))
921 mf_->begin()->removeLiveIn(li.reg);
922 if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
923 removeRange(li, LR->start, LR->end, li_, tri_);
924 return removeIntervalIfEmpty(li, li_, tri_);
927 LiveInterval::iterator LR =
928 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
930 // Livein but defined by a phi.
933 SlotIndex RemoveStart = LR->start;
934 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
935 if (LR->end > RemoveEnd)
936 // More uses past this copy? Nothing to do.
939 // If there is a last use in the same bb, we can't remove the live range.
940 // Shorten the live interval and return.
941 MachineBasicBlock *CopyMBB = CopyMI->getParent();
942 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
945 // There are other kills of the val#. Nothing to do.
946 if (!li.isOnlyLROfValNo(LR))
949 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
950 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
951 // If the live range starts in another mbb and the copy mbb is not a fall
952 // through mbb, then we can only cut the range from the beginning of the
954 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
956 if (LR->valno->def == RemoveStart) {
957 // If the def MI defines the val# and this copy is the only kill of the
958 // val#, then propagate the dead marker.
959 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
963 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
964 return removeIntervalIfEmpty(li, li_, tri_);
968 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
969 /// two virtual registers from different register classes.
971 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
973 const TargetRegisterClass *SrcRC,
974 const TargetRegisterClass *DstRC,
975 const TargetRegisterClass *NewRC) {
976 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
977 // This heuristics is good enough in practice, but it's obviously not *right*.
978 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
979 // out all but the most restrictive register classes.
980 if (NewRCCount > 4 ||
981 // Early exit if the function is fairly small, coalesce aggressively if
982 // that's the case. For really special register classes with 3 or
983 // fewer registers, be a bit more careful.
984 (li_->getFuncInstructionCount() / NewRCCount) < 8)
986 LiveInterval &SrcInt = li_->getInterval(SrcReg);
987 LiveInterval &DstInt = li_->getInterval(DstReg);
988 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
989 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
990 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
992 // Estimate *register use density*. If it doubles or more, abort.
993 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
994 mri_->use_nodbg_end());
995 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
996 mri_->use_nodbg_end());
997 unsigned NewUses = SrcUses + DstUses;
998 unsigned NewSize = SrcSize + DstSize;
999 if (SrcRC != NewRC && SrcSize > NewRCCount) {
1000 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1001 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1004 if (DstRC != NewRC && DstSize > NewRCCount) {
1005 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1006 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1013 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1014 /// which are the src/dst of the copy instruction CopyMI. This returns true
1015 /// if the copy was successfully coalesced away. If it is not currently
1016 /// possible to coalesce this interval, but it may be possible if other
1017 /// things get coalesced, then it returns true by reference in 'Again'.
1018 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1019 MachineInstr *CopyMI = TheCopy.MI;
1022 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1023 return false; // Already done.
1025 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1027 CoalescerPair CP(*tii_, *tri_);
1028 if (!CP.setRegisters(CopyMI)) {
1029 DEBUG(dbgs() << "\tNot coalescable.\n");
1033 // If they are already joined we continue.
1034 if (CP.getSrcReg() == CP.getDstReg()) {
1035 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1036 return false; // Not coalescable.
1039 DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
1041 // Enforce policies.
1043 DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
1044 // Only coalesce to allocatable physreg.
1045 if (!li_->isAllocatable(CP.getDstReg())) {
1046 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1047 return false; // Not coalescable.
1051 dbgs() << " with reg%" << CP.getDstReg();
1053 dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1054 dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1057 // Avoid constraining virtual register regclass too much.
1058 if (CP.isCrossClass()) {
1059 if (DisableCrossClassJoin) {
1060 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1063 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1064 mri_->getRegClass(CP.getSrcReg()),
1065 mri_->getRegClass(CP.getDstReg()),
1067 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1068 << CP.getNewRC()->getName() << ".\n");
1069 Again = true; // May be possible to coalesce later.
1074 // When possible, let DstReg be the larger interval.
1075 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1076 li_->getInterval(CP.getDstReg()).ranges.size())
1080 // We need to be careful about coalescing a source physical register with a
1081 // virtual register. Once the coalescing is done, it cannot be broken and
1082 // these are not spillable! If the destination interval uses are far away,
1083 // think twice about coalescing them!
1084 // FIXME: Why are we skipping this test for partial copies?
1085 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1086 if (!CP.isPartial() && CP.isPhys()) {
1087 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1089 // Don't join with physregs that have a ridiculous number of live
1090 // ranges. The data structure performance is really bad when that
1092 if (li_->hasInterval(CP.getDstReg()) &&
1093 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1096 << "\tPhysical register live interval too complicated, abort!\n");
1100 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1101 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1102 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1103 if (Length > Threshold &&
1104 std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1105 mri_->use_nodbg_end()) * Threshold < Length) {
1106 // Before giving up coalescing, if definition of source is defined by
1107 // trivial computation, try rematerializing it.
1108 if (!CP.isFlipped() &&
1109 ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1113 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1114 Again = true; // May be possible to coalesce later.
1119 // Okay, attempt to join these two intervals. On failure, this returns false.
1120 // Otherwise, if one of the intervals being joined is a physreg, this method
1121 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1122 // been modified, so we can use this information below to update aliases.
1123 if (!JoinIntervals(CP)) {
1124 // Coalescing failed.
1126 // If definition of source is defined by trivial computation, try
1127 // rematerializing it.
1128 if (!CP.isFlipped() &&
1129 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1130 CP.getDstReg(), 0, CopyMI))
1133 // If we can eliminate the copy without merging the live ranges, do so now.
1134 if (!CP.isPartial()) {
1135 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1136 RemoveCopyByCommutingDef(CP, CopyMI)) {
1137 JoinedCopies.insert(CopyMI);
1138 DEBUG(dbgs() << "\tTrivial!\n");
1143 // Otherwise, we are unable to join the intervals.
1144 DEBUG(dbgs() << "\tInterference!\n");
1145 Again = true; // May be possible to coalesce later.
1149 // Coalescing to a virtual register that is of a sub-register class of the
1150 // other. Make sure the resulting register is set to the right register class.
1151 if (CP.isCrossClass()) {
1153 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1156 // Remember to delete the copy instruction.
1157 JoinedCopies.insert(CopyMI);
1159 UpdateRegDefsUses(CP);
1161 // If we have extended the live range of a physical register, make sure we
1162 // update live-in lists as well.
1164 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1165 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1166 // ranges for this, and they are preserved.
1167 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1168 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1170 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1171 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1172 MachineBasicBlock &block = *BlockSeq[idx];
1173 if (!block.isLiveIn(CP.getDstReg()))
1174 block.addLiveIn(CP.getDstReg());
1180 // SrcReg is guarateed to be the register whose live interval that is
1182 li_->removeInterval(CP.getSrcReg());
1184 // Update regalloc hint.
1185 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1188 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1189 dbgs() << "\tJoined. Result = ";
1190 DstInt.print(dbgs(), tri_);
1198 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1199 /// compute what the resultant value numbers for each value in the input two
1200 /// ranges will be. This is complicated by copies between the two which can
1201 /// and will commonly cause multiple value numbers to be merged into one.
1203 /// VN is the value number that we're trying to resolve. InstDefiningValue
1204 /// keeps track of the new InstDefiningValue assignment for the result
1205 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1206 /// whether a value in this or other is a copy from the opposite set.
1207 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1208 /// already been assigned.
1210 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1211 /// contains the value number the copy is from.
1213 static unsigned ComputeUltimateVN(VNInfo *VNI,
1214 SmallVector<VNInfo*, 16> &NewVNInfo,
1215 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1216 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1217 SmallVector<int, 16> &ThisValNoAssignments,
1218 SmallVector<int, 16> &OtherValNoAssignments) {
1219 unsigned VN = VNI->id;
1221 // If the VN has already been computed, just return it.
1222 if (ThisValNoAssignments[VN] >= 0)
1223 return ThisValNoAssignments[VN];
1224 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1226 // If this val is not a copy from the other val, then it must be a new value
1227 // number in the destination.
1228 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1229 if (I == ThisFromOther.end()) {
1230 NewVNInfo.push_back(VNI);
1231 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1233 VNInfo *OtherValNo = I->second;
1235 // Otherwise, this *is* a copy from the RHS. If the other side has already
1236 // been computed, return it.
1237 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1238 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1240 // Mark this value number as currently being computed, then ask what the
1241 // ultimate value # of the other value is.
1242 ThisValNoAssignments[VN] = -2;
1243 unsigned UltimateVN =
1244 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1245 OtherValNoAssignments, ThisValNoAssignments);
1246 return ThisValNoAssignments[VN] = UltimateVN;
1249 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1251 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1252 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1253 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1255 // If a live interval is a physical register, check for interference with any
1256 // aliases. The interference check implemented here is a bit more conservative
1257 // than the full interfeence check below. We allow overlapping live ranges
1258 // only when one is a copy of the other.
1260 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1261 if (!li_->hasInterval(*AS))
1263 const LiveInterval &LHS = li_->getInterval(*AS);
1264 LiveInterval::const_iterator LI = LHS.begin();
1265 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1267 LI = std::lower_bound(LI, LHS.end(), RI->start);
1268 // Does LHS have an overlapping live range starting before RI?
1269 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1270 (RI->start != RI->valno->def ||
1271 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1273 dbgs() << "\t\tInterference from alias: ";
1274 LHS.print(dbgs(), tri_);
1275 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1280 // Check that LHS ranges beginning in this range are copies.
1281 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1282 if (LI->start != LI->valno->def ||
1283 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1285 dbgs() << "\t\tInterference from alias: ";
1286 LHS.print(dbgs(), tri_);
1287 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1296 // Compute the final value assignment, assuming that the live ranges can be
1298 SmallVector<int, 16> LHSValNoAssignments;
1299 SmallVector<int, 16> RHSValNoAssignments;
1300 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1301 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1302 SmallVector<VNInfo*, 16> NewVNInfo;
1304 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1305 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1307 // Loop over the value numbers of the LHS, seeing if any are defined from
1309 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1312 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
1315 // Never join with a register that has EarlyClobber redefs.
1316 if (VNI->hasRedefByEC())
1319 // DstReg is known to be a register in the LHS interval. If the src is
1320 // from the RHS interval, we can use its value #.
1321 if (!CP.isCoalescable(VNI->getCopy()))
1324 // Figure out the value # from the RHS.
1325 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1326 // The copy could be to an aliased physreg.
1328 LHSValsDefinedFromRHS[VNI] = lr->valno;
1331 // Loop over the value numbers of the RHS, seeing if any are defined from
1333 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1336 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
1339 // Never join with a register that has EarlyClobber redefs.
1340 if (VNI->hasRedefByEC())
1343 // DstReg is known to be a register in the RHS interval. If the src is
1344 // from the LHS interval, we can use its value #.
1345 if (!CP.isCoalescable(VNI->getCopy()))
1348 // Figure out the value # from the LHS.
1349 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1350 // The copy could be to an aliased physreg.
1352 RHSValsDefinedFromLHS[VNI] = lr->valno;
1355 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1356 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1357 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1359 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1362 unsigned VN = VNI->id;
1363 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1365 ComputeUltimateVN(VNI, NewVNInfo,
1366 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1367 LHSValNoAssignments, RHSValNoAssignments);
1369 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1372 unsigned VN = VNI->id;
1373 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1375 // If this value number isn't a copy from the LHS, it's a new number.
1376 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1377 NewVNInfo.push_back(VNI);
1378 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1382 ComputeUltimateVN(VNI, NewVNInfo,
1383 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1384 RHSValNoAssignments, LHSValNoAssignments);
1387 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1388 // interval lists to see if these intervals are coalescable.
1389 LiveInterval::const_iterator I = LHS.begin();
1390 LiveInterval::const_iterator IE = LHS.end();
1391 LiveInterval::const_iterator J = RHS.begin();
1392 LiveInterval::const_iterator JE = RHS.end();
1394 // Skip ahead until the first place of potential sharing.
1395 if (I != IE && J != JE) {
1396 if (I->start < J->start) {
1397 I = std::upper_bound(I, IE, J->start);
1398 if (I != LHS.begin()) --I;
1399 } else if (J->start < I->start) {
1400 J = std::upper_bound(J, JE, I->start);
1401 if (J != RHS.begin()) --J;
1405 while (I != IE && J != JE) {
1406 // Determine if these two live ranges overlap.
1408 if (I->start < J->start) {
1409 Overlaps = I->end > J->start;
1411 Overlaps = J->end > I->start;
1414 // If so, check value # info to determine if they are really different.
1416 // If the live range overlap will map to the same value number in the
1417 // result liverange, we can still coalesce them. If not, we can't.
1418 if (LHSValNoAssignments[I->valno->id] !=
1419 RHSValNoAssignments[J->valno->id])
1421 // If it's re-defined by an early clobber somewhere in the live range,
1422 // then conservatively abort coalescing.
1423 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1427 if (I->end < J->end)
1433 // Update kill info. Some live ranges are extended due to copy coalescing.
1434 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1435 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1436 VNInfo *VNI = I->first;
1437 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1438 if (VNI->hasPHIKill())
1439 NewVNInfo[LHSValID]->setHasPHIKill(true);
1442 // Update kill info. Some live ranges are extended due to copy coalescing.
1443 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1444 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1445 VNInfo *VNI = I->first;
1446 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1447 if (VNI->hasPHIKill())
1448 NewVNInfo[RHSValID]->setHasPHIKill(true);
1451 if (LHSValNoAssignments.empty())
1452 LHSValNoAssignments.push_back(-1);
1453 if (RHSValNoAssignments.empty())
1454 RHSValNoAssignments.push_back(-1);
1456 // If we get here, we know that we can coalesce the live ranges. Ask the
1457 // intervals to coalesce themselves now.
1458 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1464 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1465 // depth of the basic block (the unsigned), and then on the MBB number.
1466 struct DepthMBBCompare {
1467 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1468 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1469 // Deeper loops first
1470 if (LHS.first != RHS.first)
1471 return LHS.first > RHS.first;
1473 // Prefer blocks that are more connected in the CFG. This takes care of
1474 // the most difficult copies first while intervals are short.
1475 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1476 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1480 // As a last resort, sort by block number.
1481 return LHS.second->getNumber() < RHS.second->getNumber();
1486 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1487 std::vector<CopyRec> &TryAgain) {
1488 DEBUG(dbgs() << MBB->getName() << ":\n");
1490 std::vector<CopyRec> VirtCopies;
1491 std::vector<CopyRec> PhysCopies;
1492 std::vector<CopyRec> ImpDefCopies;
1493 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1495 MachineInstr *Inst = MII++;
1497 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1498 unsigned SrcReg, DstReg;
1499 if (Inst->isCopy()) {
1500 DstReg = Inst->getOperand(0).getReg();
1501 SrcReg = Inst->getOperand(1).getReg();
1502 } else if (Inst->isSubregToReg()) {
1503 DstReg = Inst->getOperand(0).getReg();
1504 SrcReg = Inst->getOperand(2).getReg();
1508 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1509 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1510 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1511 ImpDefCopies.push_back(CopyRec(Inst, 0));
1512 else if (SrcIsPhys || DstIsPhys)
1513 PhysCopies.push_back(CopyRec(Inst, 0));
1515 VirtCopies.push_back(CopyRec(Inst, 0));
1518 // Try coalescing implicit copies and insert_subreg <undef> first,
1519 // followed by copies to / from physical registers, then finally copies
1520 // from virtual registers to virtual registers.
1521 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1522 CopyRec &TheCopy = ImpDefCopies[i];
1524 if (!JoinCopy(TheCopy, Again))
1526 TryAgain.push_back(TheCopy);
1528 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1529 CopyRec &TheCopy = PhysCopies[i];
1531 if (!JoinCopy(TheCopy, Again))
1533 TryAgain.push_back(TheCopy);
1535 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1536 CopyRec &TheCopy = VirtCopies[i];
1538 if (!JoinCopy(TheCopy, Again))
1540 TryAgain.push_back(TheCopy);
1544 void SimpleRegisterCoalescing::joinIntervals() {
1545 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1547 std::vector<CopyRec> TryAgainList;
1548 if (loopInfo->empty()) {
1549 // If there are no loops in the function, join intervals in function order.
1550 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1552 CopyCoalesceInMBB(I, TryAgainList);
1554 // Otherwise, join intervals in inner loops before other intervals.
1555 // Unfortunately we can't just iterate over loop hierarchy here because
1556 // there may be more MBB's than BB's. Collect MBB's for sorting.
1558 // Join intervals in the function prolog first. We want to join physical
1559 // registers with virtual registers before the intervals got too long.
1560 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1561 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1562 MachineBasicBlock *MBB = I;
1563 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1566 // Sort by loop depth.
1567 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1569 // Finally, join intervals in loop nest order.
1570 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1571 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1574 // Joining intervals can allow other intervals to be joined. Iteratively join
1575 // until we make no progress.
1576 bool ProgressMade = true;
1577 while (ProgressMade) {
1578 ProgressMade = false;
1580 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1581 CopyRec &TheCopy = TryAgainList[i];
1586 bool Success = JoinCopy(TheCopy, Again);
1587 if (Success || !Again) {
1588 TheCopy.MI = 0; // Mark this one as done.
1589 ProgressMade = true;
1595 /// Return true if the two specified registers belong to different register
1596 /// classes. The registers may be either phys or virt regs.
1598 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1599 unsigned RegB) const {
1600 // Get the register classes for the first reg.
1601 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1602 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1603 "Shouldn't consider two physregs!");
1604 return !mri_->getRegClass(RegB)->contains(RegA);
1607 // Compare against the regclass for the second reg.
1608 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1609 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1610 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1611 return RegClassA != RegClassB;
1613 return !RegClassA->contains(RegB);
1616 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1617 /// between cycles Start and End or NULL if there are no uses.
1619 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1622 SlotIndex &UseIdx) const{
1623 UseIdx = SlotIndex();
1624 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1625 MachineOperand *LastUse = NULL;
1626 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1627 E = mri_->use_nodbg_end(); I != E; ++I) {
1628 MachineOperand &Use = I.getOperand();
1629 MachineInstr *UseMI = Use.getParent();
1630 if (UseMI->isIdentityCopy())
1632 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1633 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1634 // that compares higher than any other interval.
1635 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1637 UseIdx = Idx.getUseIndex();
1643 SlotIndex s = Start;
1644 SlotIndex e = End.getPrevSlot().getBaseIndex();
1646 // Skip deleted instructions
1647 MachineInstr *MI = li_->getInstructionFromIndex(e);
1648 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1649 e = e.getPrevIndex();
1650 MI = li_->getInstructionFromIndex(e);
1652 if (e < s || MI == NULL)
1655 // Ignore identity copies.
1656 if (!MI->isIdentityCopy())
1657 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1658 MachineOperand &Use = MI->getOperand(i);
1659 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1660 tri_->regsOverlap(Use.getReg(), Reg)) {
1661 UseIdx = e.getUseIndex();
1666 e = e.getPrevIndex();
1672 void SimpleRegisterCoalescing::releaseMemory() {
1673 JoinedCopies.clear();
1674 ReMatCopies.clear();
1678 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1680 mri_ = &fn.getRegInfo();
1681 tm_ = &fn.getTarget();
1682 tri_ = tm_->getRegisterInfo();
1683 tii_ = tm_->getInstrInfo();
1684 li_ = &getAnalysis<LiveIntervals>();
1685 AA = &getAnalysis<AliasAnalysis>();
1686 loopInfo = &getAnalysis<MachineLoopInfo>();
1688 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1689 << "********** Function: "
1690 << ((Value*)mf_->getFunction())->getName() << '\n');
1692 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1693 E = tri_->regclass_end(); I != E; ++I)
1694 allocatableRCRegs_.insert(std::make_pair(*I,
1695 tri_->getAllocatableSet(fn, *I)));
1697 // Join (coalesce) intervals if requested.
1698 if (EnableJoining) {
1701 dbgs() << "********** INTERVALS POST JOINING **********\n";
1702 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1704 I->second->print(dbgs(), tri_);
1710 // Perform a final pass over the instructions and compute spill weights
1711 // and remove identity moves.
1712 SmallVector<unsigned, 4> DeadDefs;
1713 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1714 mbbi != mbbe; ++mbbi) {
1715 MachineBasicBlock* mbb = mbbi;
1716 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1718 MachineInstr *MI = mii;
1719 if (JoinedCopies.count(MI)) {
1720 // Delete all coalesced copies.
1721 bool DoDelete = true;
1722 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1723 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1724 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1725 MI->getNumOperands() > 2)
1726 // Do not delete extract_subreg, insert_subreg of physical
1727 // registers unless the definition is dead. e.g.
1728 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1729 // or else the scavenger may complain. LowerSubregs will
1730 // delete them later.
1733 if (MI->allDefsAreDead()) {
1734 LiveInterval &li = li_->getInterval(SrcReg);
1735 if (!ShortenDeadCopySrcLiveRange(li, MI))
1736 ShortenDeadCopyLiveRange(li, MI);
1740 // We need the instruction to adjust liveness, so make it a KILL.
1741 if (MI->isSubregToReg()) {
1742 MI->RemoveOperand(3);
1743 MI->RemoveOperand(1);
1745 MI->setDesc(tii_->get(TargetOpcode::KILL));
1746 mii = llvm::next(mii);
1748 li_->RemoveMachineInstrFromMaps(MI);
1749 mii = mbbi->erase(mii);
1755 // Now check if this is a remat'ed def instruction which is now dead.
1756 if (ReMatDefs.count(MI)) {
1758 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1759 const MachineOperand &MO = MI->getOperand(i);
1762 unsigned Reg = MO.getReg();
1765 if (TargetRegisterInfo::isVirtualRegister(Reg))
1766 DeadDefs.push_back(Reg);
1769 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1770 !mri_->use_nodbg_empty(Reg)) {
1776 while (!DeadDefs.empty()) {
1777 unsigned DeadDef = DeadDefs.back();
1778 DeadDefs.pop_back();
1779 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1781 li_->RemoveMachineInstrFromMaps(mii);
1782 mii = mbbi->erase(mii);
1788 // If the move will be an identity move delete it
1789 if (MI->isIdentityCopy()) {
1790 unsigned SrcReg = MI->getOperand(1).getReg();
1791 if (li_->hasInterval(SrcReg)) {
1792 LiveInterval &RegInt = li_->getInterval(SrcReg);
1793 // If def of this move instruction is dead, remove its live range
1794 // from the destination register's live interval.
1795 if (MI->allDefsAreDead()) {
1796 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1797 ShortenDeadCopyLiveRange(RegInt, MI);
1800 li_->RemoveMachineInstrFromMaps(MI);
1801 mii = mbbi->erase(mii);
1808 // Check for now unnecessary kill flags.
1809 if (li_->isNotInMIMap(MI)) continue;
1810 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1811 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1812 MachineOperand &MO = MI->getOperand(i);
1813 if (!MO.isReg() || !MO.isKill()) continue;
1814 unsigned reg = MO.getReg();
1815 if (!reg || !li_->hasInterval(reg)) continue;
1816 if (!li_->getInterval(reg).killedAt(DefIdx))
1817 MO.setIsKill(false);
1826 /// print - Implement the dump method.
1827 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1831 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1832 return new SimpleRegisterCoalescing();
1835 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1836 DEFINING_FILE_FOR(SimpleRegisterCoalescing)