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 static RegisterPass<SimpleRegisterCoalescing>
63 X("simple-register-coalescing", "Simple Register Coalescing");
65 // Declare that we implement the RegisterCoalescer interface
66 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
68 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
70 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequired<AliasAnalysis>();
73 AU.addRequired<LiveIntervals>();
74 AU.addPreserved<LiveIntervals>();
75 AU.addPreserved<SlotIndexes>();
76 AU.addRequired<MachineLoopInfo>();
77 AU.addPreserved<MachineLoopInfo>();
78 AU.addPreservedID(MachineDominatorsID);
80 AU.addPreservedID(StrongPHIEliminationID);
82 AU.addPreservedID(PHIEliminationID);
83 AU.addPreservedID(TwoAddressInstructionPassID);
84 MachineFunctionPass::getAnalysisUsage(AU);
87 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
88 /// being the source and IntB being the dest, thus this defines a value number
89 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
90 /// see if we can merge these two pieces of B into a single value number,
91 /// eliminating a copy. For example:
95 /// B1 = A3 <- this copy
97 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
98 /// value number to be replaced with B0 (which simplifies the B liveinterval).
100 /// This returns true if an interval was modified.
102 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
104 MachineInstr *CopyMI) {
105 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
107 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
108 // the example above.
109 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
110 assert(BLR != IntB.end() && "Live range not found!");
111 VNInfo *BValNo = BLR->valno;
113 // Get the location that B is defined at. Two options: either this value has
114 // an unknown definition point or it is defined at CopyIdx. If unknown, we
116 if (!BValNo->getCopy()) return false;
117 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
119 // AValNo is the value number in A that defines the copy, A3 in the example.
120 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
121 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
122 assert(ALR != IntA.end() && "Live range not found!");
123 VNInfo *AValNo = ALR->valno;
124 // If it's re-defined by an early clobber somewhere in the live range, then
125 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
127 // 172 %ECX<def> = MOV32rr %reg1039<kill>
128 // 180 INLINEASM <es:subl $5,$1
129 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
131 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
132 // 188 %EAX<def> = MOV32rr %EAX<kill>
133 // 196 %ECX<def> = MOV32rr %ECX<kill>
134 // 204 %ECX<def> = MOV32rr %ECX<kill>
135 // 212 %EAX<def> = MOV32rr %EAX<kill>
136 // 220 %EAX<def> = MOV32rr %EAX
137 // 228 %reg1039<def> = MOV32rr %ECX<kill>
138 // The early clobber operand ties ECX input to the ECX def.
140 // The live interval of ECX is represented as this:
141 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
142 // The coalescer has no idea there was a def in the middle of [174,230].
143 if (AValNo->hasRedefByEC())
146 // If AValNo is defined as a copy from IntB, we can potentially process this.
147 // Get the instruction that defines this value number.
148 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
149 if (!SrcReg) return false; // Not defined by a copy.
151 // If the value number is not defined by a copy instruction, ignore it.
153 // If the source register comes from an interval other than IntB, we can't
155 if (SrcReg != IntB.reg) return false;
157 // Get the LiveRange in IntB that this value number starts with.
158 LiveInterval::iterator ValLR =
159 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
160 assert(ValLR != IntB.end() && "Live range not found!");
162 // Make sure that the end of the live range is inside the same block as
164 MachineInstr *ValLREndInst =
165 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
167 ValLREndInst->getParent() != CopyMI->getParent()) return false;
169 // Okay, we now know that ValLR ends in the same block that the CopyMI
170 // live-range starts. If there are no intervening live ranges between them in
171 // IntB, we can merge them.
172 if (ValLR+1 != BLR) return false;
174 // If a live interval is a physical register, conservatively check if any
175 // of its sub-registers is overlapping the live interval of the virtual
176 // register. If so, do not coalesce.
177 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
178 *tri_->getSubRegisters(IntB.reg)) {
179 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
180 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
182 dbgs() << "\t\tInterfere with sub-register ";
183 li_->getInterval(*SR).print(dbgs(), tri_);
190 dbgs() << "Extending: ";
191 IntB.print(dbgs(), tri_);
194 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
195 // We are about to delete CopyMI, so need to remove it as the 'instruction
196 // that defines this value #'. Update the valnum with the new defining
198 BValNo->def = FillerStart;
201 // Okay, we can merge them. We need to insert a new liverange:
202 // [ValLR.end, BLR.begin) of either value number, then we merge the
203 // two value numbers.
204 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
206 // If the IntB live range is assigned to a physical register, and if that
207 // physreg has sub-registers, update their live intervals as well.
208 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
209 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
210 LiveInterval &SRLI = li_->getInterval(*SR);
211 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
212 SRLI.getNextValue(FillerStart, 0, true,
213 li_->getVNInfoAllocator())));
217 // Okay, merge "B1" into the same value number as "B0".
218 if (BValNo != ValLR->valno) {
219 IntB.addKills(ValLR->valno, BValNo->kills);
220 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
223 dbgs() << " result = ";
224 IntB.print(dbgs(), tri_);
228 // If the source instruction was killing the source register before the
229 // merge, unset the isKill marker given the live range has been extended.
230 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
232 ValLREndInst->getOperand(UIdx).setIsKill(false);
233 ValLR->valno->removeKill(FillerStart);
236 // If the copy instruction was killing the destination register before the
237 // merge, find the last use and trim the live range. That will also add the
239 if (ALR->valno->isKill(CopyIdx))
240 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
246 /// HasOtherReachingDefs - Return true if there are definitions of IntB
247 /// other than BValNo val# that can reach uses of AValno val# of IntA.
248 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
252 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
254 if (AI->valno != AValNo) continue;
255 LiveInterval::Ranges::iterator BI =
256 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
257 if (BI != IntB.ranges.begin())
259 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
260 if (BI->valno == BValNo)
262 if (BI->start <= AI->start && BI->end > AI->start)
264 if (BI->start > AI->start && BI->start < AI->end)
272 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
273 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
275 MachineOperand &MO = MI->getOperand(i);
276 if (MO.isReg() && MO.isImplicit())
277 NewMI->addOperand(MO);
281 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
282 /// IntA being the source and IntB being the dest, thus this defines a value
283 /// number in IntB. If the source value number (in IntA) is defined by a
284 /// commutable instruction and its other operand is coalesced to the copy dest
285 /// register, see if we can transform the copy into a noop by commuting the
286 /// definition. For example,
288 /// A3 = op A2 B0<kill>
290 /// B1 = A3 <- this copy
292 /// = op A3 <- more uses
296 /// B2 = op B0 A2<kill>
298 /// B1 = B2 <- now an identify copy
300 /// = op B2 <- more uses
302 /// This returns true if an interval was modified.
304 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
306 MachineInstr *CopyMI) {
308 li_->getInstructionIndex(CopyMI).getDefIndex();
310 // FIXME: For now, only eliminate the copy by commuting its def when the
311 // source register is a virtual register. We want to guard against cases
312 // where the copy is a back edge copy and commuting the def lengthen the
313 // live interval of the source register to the entire loop.
314 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
317 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
318 // the example above.
319 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
320 assert(BLR != IntB.end() && "Live range not found!");
321 VNInfo *BValNo = BLR->valno;
323 // Get the location that B is defined at. Two options: either this value has
324 // an unknown definition point or it is defined at CopyIdx. If unknown, we
326 if (!BValNo->getCopy()) return false;
327 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
329 // AValNo is the value number in A that defines the copy, A3 in the example.
330 LiveInterval::iterator ALR =
331 IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); //
333 assert(ALR != IntA.end() && "Live range not found!");
334 VNInfo *AValNo = ALR->valno;
335 // If other defs can reach uses of this def, then it's not safe to perform
336 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
338 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
339 AValNo->isUnused() || AValNo->hasPHIKill())
341 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
342 const TargetInstrDesc &TID = DefMI->getDesc();
343 if (!TID.isCommutable())
345 // If DefMI is a two-address instruction then commuting it will change the
346 // destination register.
347 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
348 assert(DefIdx != -1);
350 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
352 unsigned Op1, Op2, NewDstIdx;
353 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
357 else if (Op2 == UseOpIdx)
362 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
363 unsigned NewReg = NewDstMO.getReg();
364 if (NewReg != IntB.reg || !NewDstMO.isKill())
367 // Make sure there are no other definitions of IntB that would reach the
368 // uses which the new definition can reach.
369 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
372 // If some of the uses of IntA.reg is already coalesced away, return false.
373 // It's not possible to determine whether it's safe to perform the coalescing.
374 for (MachineRegisterInfo::use_nodbg_iterator UI =
375 mri_->use_nodbg_begin(IntA.reg),
376 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
377 MachineInstr *UseMI = &*UI;
378 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
379 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
380 if (ULR == IntA.end())
382 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
386 // At this point we have decided that it is legal to do this
387 // transformation. Start by commuting the instruction.
388 MachineBasicBlock *MBB = DefMI->getParent();
389 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
392 if (NewMI != DefMI) {
393 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
394 MBB->insert(DefMI, NewMI);
397 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
398 NewMI->getOperand(OpIdx).setIsKill();
400 bool BHasPHIKill = BValNo->hasPHIKill();
401 SmallVector<VNInfo*, 4> BDeadValNos;
402 VNInfo::KillSet BKills;
403 std::map<SlotIndex, SlotIndex> BExtend;
405 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
414 // then do not add kills of A to the newly created B interval.
415 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
417 BExtend[ALR->end] = BLR->end;
419 // Update uses of IntA of the specific Val# with IntB.
420 bool BHasSubRegs = false;
421 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
422 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
423 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
424 UE = mri_->use_end(); UI != UE;) {
425 MachineOperand &UseMO = UI.getOperand();
426 MachineInstr *UseMI = &*UI;
428 if (JoinedCopies.count(UseMI))
430 if (UseMI->isDebugValue()) {
431 // FIXME These don't have an instruction index. Not clear we have enough
432 // info to decide whether to do this replacement or not. For now do it.
433 UseMO.setReg(NewReg);
436 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
437 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
438 if (ULR == IntA.end() || ULR->valno != AValNo)
440 UseMO.setReg(NewReg);
443 if (UseMO.isKill()) {
445 UseMO.setIsKill(false);
447 BKills.push_back(UseIdx.getDefIndex());
449 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
450 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
452 if (DstReg == IntB.reg) {
453 // This copy will become a noop. If it's defining a new val#,
454 // remove that val# as well. However this live range is being
455 // extended to the end of the existing live range defined by the copy.
456 SlotIndex DefIdx = UseIdx.getDefIndex();
457 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
458 BHasPHIKill |= DLR->valno->hasPHIKill();
459 assert(DLR->valno->def == DefIdx);
460 BDeadValNos.push_back(DLR->valno);
461 BExtend[DLR->start] = DLR->end;
462 JoinedCopies.insert(UseMI);
463 // If this is a kill but it's going to be removed, the last use
464 // of the same val# is the new kill.
470 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
471 // simply extend BLR if CopyMI doesn't end the range.
473 dbgs() << "Extending: ";
474 IntB.print(dbgs(), tri_);
477 // Remove val#'s defined by copies that will be coalesced away.
478 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
479 VNInfo *DeadVNI = BDeadValNos[i];
481 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
482 LiveInterval &SRLI = li_->getInterval(*SR);
483 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
484 SRLI.removeValNo(SRLR->valno);
487 IntB.removeValNo(BDeadValNos[i]);
490 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
491 // is updated. Kills are also updated.
492 VNInfo *ValNo = BValNo;
493 ValNo->def = AValNo->def;
495 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
496 if (ValNo->kills[j] != BLR->end)
497 BKills.push_back(ValNo->kills[j]);
499 ValNo->kills.clear();
500 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
502 if (AI->valno != AValNo) continue;
503 SlotIndex End = AI->end;
504 std::map<SlotIndex, SlotIndex>::iterator
505 EI = BExtend.find(End);
506 if (EI != BExtend.end())
508 IntB.addRange(LiveRange(AI->start, End, ValNo));
510 // If the IntB live range is assigned to a physical register, and if that
511 // physreg has sub-registers, update their live intervals as well.
513 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
514 LiveInterval &SRLI = li_->getInterval(*SR);
515 SRLI.MergeInClobberRange(*li_, AI->start, End,
516 li_->getVNInfoAllocator());
520 IntB.addKills(ValNo, BKills);
521 ValNo->setHasPHIKill(BHasPHIKill);
524 dbgs() << " result = ";
525 IntB.print(dbgs(), tri_);
526 dbgs() << "\nShortening: ";
527 IntA.print(dbgs(), tri_);
530 IntA.removeValNo(AValNo);
533 dbgs() << " result = ";
534 IntA.print(dbgs(), tri_);
542 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
543 /// fallthoughs to SuccMBB.
544 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
545 MachineBasicBlock *SuccMBB,
546 const TargetInstrInfo *tii_) {
549 MachineBasicBlock *TBB = 0, *FBB = 0;
550 SmallVector<MachineOperand, 4> Cond;
551 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
552 MBB->isSuccessor(SuccMBB);
555 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
556 /// from a physical register live interval as well as from the live intervals
557 /// of its sub-registers.
558 static void removeRange(LiveInterval &li,
559 SlotIndex Start, SlotIndex End,
560 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
561 li.removeRange(Start, End, true);
562 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
563 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
564 if (!li_->hasInterval(*SR))
566 LiveInterval &sli = li_->getInterval(*SR);
567 SlotIndex RemoveStart = Start;
568 SlotIndex RemoveEnd = Start;
570 while (RemoveEnd != End) {
571 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
574 RemoveEnd = (LR->end < End) ? LR->end : End;
575 sli.removeRange(RemoveStart, RemoveEnd, true);
576 RemoveStart = RemoveEnd;
582 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
583 /// as the copy instruction, trim the live interval to the last use and return
586 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
587 MachineBasicBlock *CopyMBB,
589 const LiveRange *LR) {
590 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
591 SlotIndex LastUseIdx;
592 MachineOperand *LastUse =
593 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
595 MachineInstr *LastUseMI = LastUse->getParent();
596 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
603 // r1025<dead> = r1024<kill>
604 if (MBBStart < LR->end)
605 removeRange(li, MBBStart, LR->end, li_, tri_);
609 // There are uses before the copy, just shorten the live range to the end
611 LastUse->setIsKill();
612 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
613 LR->valno->addKill(LastUseIdx.getDefIndex());
614 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
615 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
617 // Last use is itself an identity code.
618 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
619 LastUseMI->getOperand(DeadIdx).setIsDead();
625 if (LR->start <= MBBStart && LR->end > MBBStart) {
626 if (LR->start == li_->getZeroIndex()) {
627 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
628 // Live-in to the function but dead. Remove it from entry live-in set.
629 mf_->begin()->removeLiveIn(li.reg);
631 // FIXME: Shorten intervals in BBs that reaches this BB.
637 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
638 /// computation, replace the copy by rematerialize the definition.
639 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
642 MachineInstr *CopyMI) {
643 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
644 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
645 assert(SrcLR != SrcInt.end() && "Live range not found!");
646 VNInfo *ValNo = SrcLR->valno;
647 // If other defs can reach uses of this def, then it's not safe to perform
648 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
650 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
651 ValNo->isUnused() || ValNo->hasPHIKill())
653 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
654 const TargetInstrDesc &TID = DefMI->getDesc();
655 if (!TID.isAsCheapAsAMove())
657 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
659 bool SawStore = false;
660 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
662 if (TID.getNumDefs() != 1)
664 if (!DefMI->isImplicitDef()) {
665 // Make sure the copy destination register class fits the instruction
666 // definition register class. The mismatch can happen as a result of earlier
667 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
668 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
669 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
670 if (mri_->getRegClass(DstReg) != RC)
672 } else if (!RC->contains(DstReg))
676 // If destination register has a sub-register index on it, make sure it mtches
677 // the instruction register class.
679 const TargetInstrDesc &TID = DefMI->getDesc();
680 if (TID.getNumDefs() != 1)
682 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
683 const TargetRegisterClass *DstSubRC =
684 DstRC->getSubRegisterRegClass(DstSubIdx);
685 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
688 else if (DefRC != DstSubRC)
692 SlotIndex DefIdx = CopyIdx.getDefIndex();
693 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
694 DLR->valno->setCopy(0);
695 // Don't forget to update sub-register intervals.
696 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
697 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
698 if (!li_->hasInterval(*SR))
700 const LiveRange *DLR =
701 li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
702 if (DLR && DLR->valno->getCopy() == CopyMI)
703 DLR->valno->setCopy(0);
707 // If copy kills the source register, find the last use and propagate
709 bool checkForDeadDef = false;
710 MachineBasicBlock *MBB = CopyMI->getParent();
711 if (SrcLR->valno->isKill(DefIdx))
712 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
713 checkForDeadDef = true;
716 MachineBasicBlock::iterator MII =
717 llvm::next(MachineBasicBlock::iterator(CopyMI));
718 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, tri_);
719 MachineInstr *NewMI = prior(MII);
721 if (checkForDeadDef) {
722 // PR4090 fix: Trim interval failed because there was no use of the
723 // source interval in this MBB. If the def is in this MBB too then we
724 // should mark it dead:
725 if (DefMI->getParent() == MBB) {
726 DefMI->addRegisterDead(SrcInt.reg, tri_);
727 SrcLR->end = SrcLR->start.getNextSlot();
731 // CopyMI may have implicit operands, transfer them over to the newly
732 // rematerialized instruction. And update implicit def interval valnos.
733 for (unsigned i = CopyMI->getDesc().getNumOperands(),
734 e = CopyMI->getNumOperands(); i != e; ++i) {
735 MachineOperand &MO = CopyMI->getOperand(i);
736 if (MO.isReg() && MO.isImplicit())
737 NewMI->addOperand(MO);
738 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
739 unsigned Reg = MO.getReg();
740 const LiveRange *DLR =
741 li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
742 if (DLR && DLR->valno->getCopy() == CopyMI)
743 DLR->valno->setCopy(0);
744 // Handle subregs as well
745 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
746 for (const unsigned* SR = tri_->getSubRegisters(Reg); *SR; ++SR) {
747 if (!li_->hasInterval(*SR))
749 const LiveRange *DLR =
750 li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
751 if (DLR && DLR->valno->getCopy() == CopyMI)
752 DLR->valno->setCopy(0);
758 TransferImplicitOps(CopyMI, NewMI);
759 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
760 CopyMI->eraseFromParent();
761 ReMatCopies.insert(CopyMI);
762 ReMatDefs.insert(DefMI);
763 DEBUG(dbgs() << "Remat: " << *NewMI);
768 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
769 /// update the subregister number if it is not zero. If DstReg is a
770 /// physical register and the existing subregister number of the def / use
771 /// being updated is not zero, make sure to set it to the correct physical
774 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
776 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
777 if (DstIsPhys && SubIdx) {
778 // Figure out the real physical register we are updating with.
779 DstReg = tri_->getSubReg(DstReg, SubIdx);
783 // Copy the register use-list before traversing it. We may be adding operands
784 // and invalidating pointers.
785 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
786 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
787 E = mri_->reg_end(); I != E; ++I)
788 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
790 for (unsigned N=0; N != reglist.size(); ++N) {
791 MachineInstr *UseMI = reglist[N].first;
792 MachineOperand &O = UseMI->getOperand(reglist[N].second);
793 unsigned OldSubIdx = O.getSubReg();
795 unsigned UseDstReg = DstReg;
797 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
799 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
800 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
801 CopySrcSubIdx, CopyDstSubIdx) &&
802 CopySrcReg != CopyDstReg &&
803 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
804 // If the use is a copy and it won't be coalesced away, and its source
805 // is defined by a trivial computation, try to rematerialize it instead.
806 if (!JoinedCopies.count(UseMI) &&
807 ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
808 CopyDstSubIdx, UseMI))
815 // Def and kill of subregister of a virtual register actually defs and
816 // kills the whole register. Add imp-defs and imp-kills as needed.
819 UseMI->addRegisterDead(DstReg, tri_, true);
821 UseMI->addRegisterDefined(DstReg, tri_);
822 } else if (!O.isUndef() &&
824 UseMI->isRegTiedToDefOperand(&O-&UseMI->getOperand(0))))
825 UseMI->addRegisterKilled(DstReg, tri_, true);
827 DEBUG(dbgs() << "\t\tupdated: " << li_->getInstructionIndex(UseMI)
832 // Sub-register indexes goes from small to large. e.g.
833 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
834 // EAX: 1 -> AL, 2 -> AX
835 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
836 // sub-register 2 is also AX.
837 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
838 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
843 DEBUG(dbgs() << "\t\tupdated: " << li_->getInstructionIndex(UseMI)
846 // After updating the operand, check if the machine instruction has
847 // become a copy. If so, update its val# information.
848 if (JoinedCopies.count(UseMI))
851 const TargetInstrDesc &TID = UseMI->getDesc();
852 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
853 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
854 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
855 CopySrcSubIdx, CopyDstSubIdx) &&
856 CopySrcReg != CopyDstReg &&
857 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
858 allocatableRegs_[CopyDstReg])) {
859 LiveInterval &LI = li_->getInterval(CopyDstReg);
861 li_->getInstructionIndex(UseMI).getDefIndex();
862 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
863 if (DLR->valno->def == DefIdx)
864 DLR->valno->setCopy(UseMI);
870 /// removeIntervalIfEmpty - Check if the live interval of a physical register
871 /// is empty, if so remove it and also remove the empty intervals of its
872 /// sub-registers. Return true if live interval is removed.
873 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
874 const TargetRegisterInfo *tri_) {
876 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
877 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
878 if (!li_->hasInterval(*SR))
880 LiveInterval &sli = li_->getInterval(*SR);
882 li_->removeInterval(*SR);
884 li_->removeInterval(li.reg);
890 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
891 /// Return true if live interval is removed.
892 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
893 MachineInstr *CopyMI) {
894 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
895 LiveInterval::iterator MLR =
896 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
898 return false; // Already removed by ShortenDeadCopySrcLiveRange.
899 SlotIndex RemoveStart = MLR->start;
900 SlotIndex RemoveEnd = MLR->end;
901 SlotIndex DefIdx = CopyIdx.getDefIndex();
902 // Remove the liverange that's defined by this.
903 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
904 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
905 return removeIntervalIfEmpty(li, li_, tri_);
910 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
911 /// the val# it defines. If the live interval becomes empty, remove it as well.
912 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
913 MachineInstr *DefMI) {
914 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
915 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
916 if (DefIdx != MLR->valno->def)
918 li.removeValNo(MLR->valno);
919 return removeIntervalIfEmpty(li, li_, tri_);
922 /// PropagateDeadness - Propagate the dead marker to the instruction which
923 /// defines the val#.
924 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
925 SlotIndex &LRStart, LiveIntervals *li_,
926 const TargetRegisterInfo* tri_) {
927 MachineInstr *DefMI =
928 li_->getInstructionFromIndex(LRStart.getDefIndex());
929 if (DefMI && DefMI != CopyMI) {
930 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
932 DefMI->getOperand(DeadIdx).setIsDead();
934 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
935 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
936 LRStart = LRStart.getNextSlot();
940 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
941 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
942 /// ends the live range there. If there isn't another use, then this live range
943 /// is dead. Return true if live interval is removed.
945 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
946 MachineInstr *CopyMI) {
947 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
948 if (CopyIdx == SlotIndex()) {
949 // FIXME: special case: function live in. It can be a general case if the
950 // first instruction index starts at > 0 value.
951 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
952 // Live-in to the function but dead. Remove it from entry live-in set.
953 if (mf_->begin()->isLiveIn(li.reg))
954 mf_->begin()->removeLiveIn(li.reg);
955 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
956 removeRange(li, LR->start, LR->end, li_, tri_);
957 return removeIntervalIfEmpty(li, li_, tri_);
960 LiveInterval::iterator LR =
961 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
963 // Livein but defined by a phi.
966 SlotIndex RemoveStart = LR->start;
967 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
968 if (LR->end > RemoveEnd)
969 // More uses past this copy? Nothing to do.
972 // If there is a last use in the same bb, we can't remove the live range.
973 // Shorten the live interval and return.
974 MachineBasicBlock *CopyMBB = CopyMI->getParent();
975 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
978 // There are other kills of the val#. Nothing to do.
979 if (!li.isOnlyLROfValNo(LR))
982 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
983 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
984 // If the live range starts in another mbb and the copy mbb is not a fall
985 // through mbb, then we can only cut the range from the beginning of the
987 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
989 if (LR->valno->def == RemoveStart) {
990 // If the def MI defines the val# and this copy is the only kill of the
991 // val#, then propagate the dead marker.
992 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
995 if (LR->valno->isKill(RemoveEnd))
996 LR->valno->removeKill(RemoveEnd);
999 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
1000 return removeIntervalIfEmpty(li, li_, tri_);
1003 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
1004 /// from an implicit def to another register can be coalesced away.
1005 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
1007 LiveInterval &ImpLi) const{
1008 if (!CopyMI->killsRegister(ImpLi.reg))
1010 // Make sure this is the only use.
1011 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1012 UE = mri_->use_end(); UI != UE;) {
1013 MachineInstr *UseMI = &*UI;
1015 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1023 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1024 /// a virtual destination register with physical source register.
1026 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1027 MachineBasicBlock *CopyMBB,
1028 LiveInterval &DstInt,
1029 LiveInterval &SrcInt) {
1030 // If the virtual register live interval is long but it has low use desity,
1031 // do not join them, instead mark the physical register as its allocation
1033 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1034 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1035 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1036 if (Length > Threshold &&
1037 std::distance(mri_->use_nodbg_begin(DstInt.reg),
1038 mri_->use_nodbg_end()) * Threshold < Length)
1041 // If the virtual register live interval extends into a loop, turn down
1044 li_->getInstructionIndex(CopyMI).getDefIndex();
1045 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1047 // Let's see if the virtual register live interval extends into the loop.
1048 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1049 assert(DLR != DstInt.end() && "Live range not found!");
1050 DLR = DstInt.FindLiveRangeContaining(DLR->end.getNextSlot());
1051 if (DLR != DstInt.end()) {
1052 CopyMBB = li_->getMBBFromIndex(DLR->start);
1053 L = loopInfo->getLoopFor(CopyMBB);
1057 if (!L || Length <= Threshold)
1060 SlotIndex UseIdx = CopyIdx.getUseIndex();
1061 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1062 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1063 if (loopInfo->getLoopFor(SMBB) != L) {
1064 if (!loopInfo->isLoopHeader(CopyMBB))
1066 // If vr's live interval extends pass the loop header, do not join.
1067 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1068 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1069 MachineBasicBlock *SuccMBB = *SI;
1070 if (SuccMBB == CopyMBB)
1072 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1073 li_->getMBBEndIdx(SuccMBB)))
1080 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1081 /// copy from a virtual source register to a physical destination register.
1083 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1084 MachineBasicBlock *CopyMBB,
1085 LiveInterval &DstInt,
1086 LiveInterval &SrcInt) {
1087 // If the virtual register live interval is long but it has low use density,
1088 // do not join them, instead mark the physical register as its allocation
1090 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1091 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1092 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1093 if (Length > Threshold &&
1094 std::distance(mri_->use_nodbg_begin(SrcInt.reg),
1095 mri_->use_nodbg_end()) * Threshold < Length)
1099 // Must be implicit_def.
1102 // If the virtual register live interval is defined or cross a loop, turn
1103 // down aggressiveness.
1105 li_->getInstructionIndex(CopyMI).getDefIndex();
1106 SlotIndex UseIdx = CopyIdx.getUseIndex();
1107 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1108 assert(SLR != SrcInt.end() && "Live range not found!");
1109 SLR = SrcInt.FindLiveRangeContaining(SLR->start.getPrevSlot());
1110 if (SLR == SrcInt.end())
1112 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1113 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1115 if (!L || Length <= Threshold)
1118 if (loopInfo->getLoopFor(CopyMBB) != L) {
1119 if (SMBB != L->getLoopLatch())
1121 // If vr's live interval is extended from before the loop latch, do not
1123 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1124 PE = SMBB->pred_end(); PI != PE; ++PI) {
1125 MachineBasicBlock *PredMBB = *PI;
1126 if (PredMBB == SMBB)
1128 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1129 li_->getMBBEndIdx(PredMBB)))
1136 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1137 /// two virtual registers from different register classes.
1139 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
1141 const TargetRegisterClass *SrcRC,
1142 const TargetRegisterClass *DstRC,
1143 const TargetRegisterClass *NewRC) {
1144 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
1145 // This heuristics is good enough in practice, but it's obviously not *right*.
1146 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
1147 // out all but the most restrictive register classes.
1148 if (NewRCCount > 4 ||
1149 // Early exit if the function is fairly small, coalesce aggressively if
1150 // that's the case. For really special register classes with 3 or
1151 // fewer registers, be a bit more careful.
1152 (li_->getFuncInstructionCount() / NewRCCount) < 8)
1154 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1155 LiveInterval &DstInt = li_->getInterval(DstReg);
1156 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
1157 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
1158 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
1160 // Estimate *register use density*. If it doubles or more, abort.
1161 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
1162 mri_->use_nodbg_end());
1163 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
1164 mri_->use_nodbg_end());
1165 unsigned NewUses = SrcUses + DstUses;
1166 unsigned NewSize = SrcSize + DstSize;
1167 if (SrcRC != NewRC && SrcSize > NewRCCount) {
1168 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1169 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1172 if (DstRC != NewRC && DstSize > NewRCCount) {
1173 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1174 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1180 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1181 /// register with a physical register, check if any of the virtual register
1182 /// operand is a sub-register use or def. If so, make sure it won't result
1183 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1184 /// vr1024 = extract_subreg vr1025, 1
1186 /// vr1024 = mov8rr AH
1187 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1188 /// AH does not have a super-reg whose sub-register 1 is AH.
1190 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1193 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1194 E = mri_->reg_end(); I != E; ++I) {
1195 MachineOperand &O = I.getOperand();
1198 MachineInstr *MI = &*I;
1199 if (MI == CopyMI || JoinedCopies.count(MI))
1201 unsigned SubIdx = O.getSubReg();
1202 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1204 if (MI->isExtractSubreg()) {
1205 SubIdx = MI->getOperand(2).getImm();
1206 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1209 unsigned SrcReg = MI->getOperand(1).getReg();
1210 const TargetRegisterClass *RC =
1211 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1212 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1213 : mri_->getRegClass(SrcReg);
1214 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1218 if (MI->isInsertSubreg() || MI->isSubregToReg()) {
1219 SubIdx = MI->getOperand(3).getImm();
1220 if (VirtReg == MI->getOperand(0).getReg()) {
1221 if (!tri_->getSubReg(PhysReg, SubIdx))
1224 unsigned DstReg = MI->getOperand(0).getReg();
1225 const TargetRegisterClass *RC =
1226 TargetRegisterInfo::isPhysicalRegister(DstReg)
1227 ? tri_->getPhysicalRegisterRegClass(DstReg)
1228 : mri_->getRegClass(DstReg);
1229 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1238 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1239 /// an extract_subreg where dst is a physical register, e.g.
1240 /// cl = EXTRACT_SUBREG reg1024, 1
1242 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1243 unsigned SrcReg, unsigned SubIdx,
1244 unsigned &RealDstReg) {
1245 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1246 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1247 assert(RealDstReg && "Invalid extract_subreg instruction!");
1249 LiveInterval &RHS = li_->getInterval(SrcReg);
1250 // For this type of EXTRACT_SUBREG, conservatively
1251 // check if the live interval of the source register interfere with the
1252 // actual super physical register we are trying to coalesce with.
1253 if (li_->hasInterval(RealDstReg) &&
1254 RHS.overlaps(li_->getInterval(RealDstReg))) {
1256 dbgs() << "\t\tInterfere with register ";
1257 li_->getInterval(RealDstReg).print(dbgs(), tri_);
1259 return false; // Not coalescable
1261 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1262 // Do not check DstReg or its sub-register. JoinIntervals() will take care
1264 if (*SR != DstReg &&
1265 !tri_->isSubRegister(DstReg, *SR) &&
1266 li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1268 dbgs() << "\t\tInterfere with sub-register ";
1269 li_->getInterval(*SR).print(dbgs(), tri_);
1271 return false; // Not coalescable
1276 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1277 /// an insert_subreg where src is a physical register, e.g.
1278 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1280 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1281 unsigned SrcReg, unsigned SubIdx,
1282 unsigned &RealSrcReg) {
1283 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1284 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1285 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1287 LiveInterval &LHS = li_->getInterval(DstReg);
1288 if (li_->hasInterval(RealSrcReg) &&
1289 LHS.overlaps(li_->getInterval(RealSrcReg))) {
1291 dbgs() << "\t\tInterfere with register ";
1292 li_->getInterval(RealSrcReg).print(dbgs(), tri_);
1294 return false; // Not coalescable
1296 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1297 // Do not check SrcReg or its sub-register. JoinIntervals() will take care
1299 if (*SR != SrcReg &&
1300 !tri_->isSubRegister(SrcReg, *SR) &&
1301 li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1303 dbgs() << "\t\tInterfere with sub-register ";
1304 li_->getInterval(*SR).print(dbgs(), tri_);
1306 return false; // Not coalescable
1311 /// getRegAllocPreference - Return register allocation preference register.
1313 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1314 MachineRegisterInfo *MRI,
1315 const TargetRegisterInfo *TRI) {
1316 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1318 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1319 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1322 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1323 /// which are the src/dst of the copy instruction CopyMI. This returns true
1324 /// if the copy was successfully coalesced away. If it is not currently
1325 /// possible to coalesce this interval, but it may be possible if other
1326 /// things get coalesced, then it returns true by reference in 'Again'.
1327 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1328 MachineInstr *CopyMI = TheCopy.MI;
1331 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1332 return false; // Already done.
1334 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1336 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1337 bool isExtSubReg = CopyMI->isExtractSubreg();
1338 bool isInsSubReg = CopyMI->isInsertSubreg();
1339 bool isSubRegToReg = CopyMI->isSubregToReg();
1340 unsigned SubIdx = 0;
1342 DstReg = CopyMI->getOperand(0).getReg();
1343 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1344 SrcReg = CopyMI->getOperand(1).getReg();
1345 SrcSubIdx = CopyMI->getOperand(2).getImm();
1346 } else if (isInsSubReg || isSubRegToReg) {
1347 DstReg = CopyMI->getOperand(0).getReg();
1348 DstSubIdx = CopyMI->getOperand(3).getImm();
1349 SrcReg = CopyMI->getOperand(2).getReg();
1350 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1351 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1352 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1353 // coalesced to a larger register so the subreg indices cancel out.
1354 DEBUG(dbgs() << "\tSource of insert_subreg or subreg_to_reg is already "
1355 "coalesced to another register.\n");
1356 return false; // Not coalescable.
1358 } else if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1359 if (SrcSubIdx && DstSubIdx && SrcSubIdx != DstSubIdx) {
1360 // e.g. %reg16404:1<def> = MOV8rr %reg16412:2<kill>
1362 return false; // Not coalescable.
1365 llvm_unreachable("Unrecognized copy instruction!");
1368 // If they are already joined we continue.
1369 if (SrcReg == DstReg) {
1370 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1371 return false; // Not coalescable.
1374 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1375 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1377 // If they are both physical registers, we cannot join them.
1378 if (SrcIsPhys && DstIsPhys) {
1379 DEBUG(dbgs() << "\tCan not coalesce physregs.\n");
1380 return false; // Not coalescable.
1383 // We only join virtual registers with allocatable physical registers.
1384 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1385 DEBUG(dbgs() << "\tSrc reg is unallocatable physreg.\n");
1386 return false; // Not coalescable.
1388 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1389 DEBUG(dbgs() << "\tDst reg is unallocatable physreg.\n");
1390 return false; // Not coalescable.
1393 // We cannot handle dual subreg indices and mismatched classes at the same
1395 if (SrcSubIdx && DstSubIdx && differingRegisterClasses(SrcReg, DstReg)) {
1396 DEBUG(dbgs() << "\tCannot handle subreg indices and mismatched classes.\n");
1400 // Check that a physical source register is compatible with dst regclass
1402 unsigned SrcSubReg = SrcSubIdx ?
1403 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1404 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1405 const TargetRegisterClass *DstSubRC = DstRC;
1407 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1408 assert(DstSubRC && "Illegal subregister index");
1409 if (!DstSubRC->contains(SrcSubReg)) {
1410 DEBUG(dbgs() << "\tIncompatible destination regclass: "
1411 << tri_->getName(SrcSubReg) << " not in "
1412 << DstSubRC->getName() << ".\n");
1413 return false; // Not coalescable.
1417 // Check that a physical dst register is compatible with source regclass
1419 unsigned DstSubReg = DstSubIdx ?
1420 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1421 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1422 const TargetRegisterClass *SrcSubRC = SrcRC;
1424 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1425 assert(SrcSubRC && "Illegal subregister index");
1426 if (!SrcSubRC->contains(DstSubReg)) {
1427 DEBUG(dbgs() << "\tIncompatible source regclass: "
1428 << tri_->getName(DstSubReg) << " not in "
1429 << SrcSubRC->getName() << ".\n");
1431 return false; // Not coalescable.
1435 // Should be non-null only when coalescing to a sub-register class.
1436 bool CrossRC = false;
1437 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1438 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1439 const TargetRegisterClass *NewRC = NULL;
1440 unsigned RealDstReg = 0;
1441 unsigned RealSrcReg = 0;
1442 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1443 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1444 if (SrcIsPhys && isExtSubReg) {
1445 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1446 // coalesced with AX.
1447 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1449 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1450 // coalesced to a larger register so the subreg indices cancel out.
1451 if (DstSubIdx != SubIdx) {
1452 DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1453 return false; // Not coalescable.
1456 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1458 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1459 // EAX = INSERT_SUBREG EAX, r1024, 0
1460 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1462 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1463 // coalesced to a larger register so the subreg indices cancel out.
1464 if (SrcSubIdx != SubIdx) {
1465 DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1466 return false; // Not coalescable.
1469 DstReg = tri_->getSubReg(DstReg, SubIdx);
1471 } else if ((DstIsPhys && isExtSubReg) ||
1472 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1473 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1474 DEBUG(dbgs() << "\tSrc of extract_subreg already coalesced with reg"
1475 << " of a super-class.\n");
1476 return false; // Not coalescable.
1479 // FIXME: The following checks are somewhat conservative. Perhaps a better
1480 // way to implement this is to treat this as coalescing a vr with the
1481 // super physical register.
1483 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1484 return false; // Not coalescable
1486 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1487 return false; // Not coalescable
1491 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1492 : CopyMI->getOperand(2).getSubReg();
1494 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1495 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1496 // coalesced to a larger register so the subreg indices cancel out.
1497 // Also check if the other larger register is of the same register
1498 // class as the would be resulting register.
1501 DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1502 return false; // Not coalescable.
1506 if (!DstIsPhys && !SrcIsPhys) {
1507 if (isInsSubReg || isSubRegToReg) {
1508 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1509 } else // extract_subreg {
1510 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1513 DEBUG(dbgs() << "\t Conflicting sub-register indices.\n");
1514 return false; // Not coalescable
1517 if (!isWinToJoinCrossClass(SrcReg, DstReg, SrcRC, DstRC, NewRC)) {
1518 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1519 << SrcRC->getName() << "/"
1520 << DstRC->getName() << " -> "
1521 << NewRC->getName() << ".\n");
1522 Again = true; // May be possible to coalesce later.
1527 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1528 if (DisableCrossClassJoin)
1532 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1533 // with another? If it's the resulting destination register, then
1534 // the subidx must be propagated to uses (but only those defined
1535 // by the EXTRACT_SUBREG). If it's being coalesced into another
1536 // register, it should be safe because register is assumed to have
1537 // the register class of the super-register.
1539 // Process moves where one of the registers have a sub-register index.
1540 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1541 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1542 SubIdx = DstMO->getSubReg();
1544 if (SrcMO->getSubReg())
1545 // FIXME: can we handle this?
1547 // This is not an insert_subreg but it looks like one.
1548 // e.g. %reg1024:4 = MOV32rr %EAX
1551 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1552 return false; // Not coalescable
1556 SubIdx = SrcMO->getSubReg();
1558 // This is not a extract_subreg but it looks like one.
1559 // e.g. %cl = MOV16rr %reg1024:1
1562 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1563 return false; // Not coalescable
1569 // Now determine the register class of the joined register.
1570 if (!SrcIsPhys && !DstIsPhys) {
1573 SubIdx ? tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx) : SrcRC;
1574 } else if (isInsSubReg) {
1576 SubIdx ? tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx) : DstRC;
1578 NewRC = getCommonSubClass(SrcRC, DstRC);
1582 DEBUG(dbgs() << "\tDisjoint regclasses: "
1583 << SrcRC->getName() << ", "
1584 << DstRC->getName() << ".\n");
1585 return false; // Not coalescable.
1588 // If we are joining two virtual registers and the resulting register
1589 // class is more restrictive (fewer register, smaller size). Check if it's
1590 // worth doing the merge.
1591 if (!isWinToJoinCrossClass(SrcReg, DstReg, SrcRC, DstRC, NewRC)) {
1592 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1593 << SrcRC->getName() << "/"
1594 << DstRC->getName() << " -> "
1595 << NewRC->getName() << ".\n");
1596 // Allow the coalescer to try again in case either side gets coalesced to
1597 // a physical register that's compatible with the other side. e.g.
1598 // r1024 = MOV32to32_ r1025
1599 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1600 Again = true; // May be possible to coalesce later.
1606 // Will it create illegal extract_subreg / insert_subreg?
1607 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1609 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1612 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1613 LiveInterval &DstInt = li_->getInterval(DstReg);
1614 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1615 "Register mapping is horribly broken!");
1618 dbgs() << "\t\tInspecting ";
1619 if (SrcRC) dbgs() << SrcRC->getName() << ": ";
1620 SrcInt.print(dbgs(), tri_);
1621 dbgs() << "\n\t\t and ";
1622 if (DstRC) dbgs() << DstRC->getName() << ": ";
1623 DstInt.print(dbgs(), tri_);
1627 // Save a copy of the virtual register live interval. We'll manually
1628 // merge this into the "real" physical register live interval this is
1630 OwningPtr<LiveInterval> SavedLI;
1632 SavedLI.reset(li_->dupInterval(&SrcInt));
1633 else if (RealSrcReg)
1634 SavedLI.reset(li_->dupInterval(&DstInt));
1636 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1637 // Check if it is necessary to propagate "isDead" property.
1638 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1639 bool isDead = mopd->isDead();
1641 // We need to be careful about coalescing a source physical register with a
1642 // virtual register. Once the coalescing is done, it cannot be broken and
1643 // these are not spillable! If the destination interval uses are far away,
1644 // think twice about coalescing them!
1645 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1646 // If the virtual register live interval is long but it has low use
1647 // density, do not join them, instead mark the physical register as its
1648 // allocation preference.
1649 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1650 LiveInterval &JoinPInt = SrcIsPhys ? SrcInt : DstInt;
1651 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1652 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1654 // Don't join with physregs that have a ridiculous number of live
1655 // ranges. The data structure performance is really bad when that
1657 if (JoinPInt.ranges.size() > 1000) {
1658 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1661 << "\tPhysical register live interval too complicated, abort!\n");
1665 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1666 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1667 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1668 if (Length > Threshold &&
1669 std::distance(mri_->use_nodbg_begin(JoinVReg),
1670 mri_->use_nodbg_end()) * Threshold < Length) {
1671 // Before giving up coalescing, if definition of source is defined by
1672 // trivial computation, try rematerializing it.
1673 if (ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1676 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1678 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1679 Again = true; // May be possible to coalesce later.
1685 // Okay, attempt to join these two intervals. On failure, this returns false.
1686 // Otherwise, if one of the intervals being joined is a physreg, this method
1687 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1688 // been modified, so we can use this information below to update aliases.
1689 bool Swapped = false;
1690 // If SrcInt is implicitly defined, it's safe to coalesce.
1691 if (SrcInt.empty()) {
1692 if (!CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1693 // Only coalesce an empty interval (defined by implicit_def) with
1694 // another interval which has a valno defined by the CopyMI and the CopyMI
1695 // is a kill of the implicit def.
1696 DEBUG(dbgs() << "\tNot profitable!\n");
1699 } else if (!JoinIntervals(DstInt, SrcInt, Swapped)) {
1700 // Coalescing failed.
1702 // If definition of source is defined by trivial computation, try
1703 // rematerializing it.
1704 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1705 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1708 // If we can eliminate the copy without merging the live ranges, do so now.
1709 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1710 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1711 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1712 JoinedCopies.insert(CopyMI);
1713 DEBUG(dbgs() << "\tTrivial!\n");
1717 // Otherwise, we are unable to join the intervals.
1718 DEBUG(dbgs() << "\tInterference!\n");
1719 Again = true; // May be possible to coalesce later.
1723 LiveInterval *ResSrcInt = &SrcInt;
1724 LiveInterval *ResDstInt = &DstInt;
1726 std::swap(SrcReg, DstReg);
1727 std::swap(ResSrcInt, ResDstInt);
1729 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1730 "LiveInterval::join didn't work right!");
1732 // If we're about to merge live ranges into a physical register live interval,
1733 // we have to update any aliased register's live ranges to indicate that they
1734 // have clobbered values for this range.
1735 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1736 // If this is a extract_subreg where dst is a physical register, e.g.
1737 // cl = EXTRACT_SUBREG reg1024, 1
1738 // then create and update the actual physical register allocated to RHS.
1739 if (RealDstReg || RealSrcReg) {
1740 LiveInterval &RealInt =
1741 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1742 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1743 E = SavedLI->vni_end(); I != E; ++I) {
1744 const VNInfo *ValNo = *I;
1745 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1746 false, // updated at *
1747 li_->getVNInfoAllocator());
1748 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1749 RealInt.addKills(NewValNo, ValNo->kills);
1750 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1752 RealInt.weight += SavedLI->weight;
1753 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1756 // Update the liveintervals of sub-registers.
1757 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1758 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, *ResSrcInt,
1759 li_->getVNInfoAllocator());
1762 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1763 // larger super-register.
1764 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1765 !SrcIsPhys && !DstIsPhys) {
1766 if ((isExtSubReg && !Swapped) ||
1767 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1768 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1769 std::swap(SrcReg, DstReg);
1770 std::swap(ResSrcInt, ResDstInt);
1774 // Coalescing to a virtual register that is of a sub-register class of the
1775 // other. Make sure the resulting register is set to the right register class.
1779 // This may happen even if it's cross-rc coalescing. e.g.
1780 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1781 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1782 // be allocate a register from GR64_ABCD.
1784 mri_->setRegClass(DstReg, NewRC);
1786 // Remember to delete the copy instruction.
1787 JoinedCopies.insert(CopyMI);
1789 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1791 // If we have extended the live range of a physical register, make sure we
1792 // update live-in lists as well.
1793 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1794 const LiveInterval &VRegInterval = li_->getInterval(SrcReg);
1795 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1796 for (LiveInterval::const_iterator I = VRegInterval.begin(),
1797 E = VRegInterval.end(); I != E; ++I ) {
1798 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1799 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1800 MachineBasicBlock &block = *BlockSeq[idx];
1801 if (!block.isLiveIn(DstReg))
1802 block.addLiveIn(DstReg);
1808 // SrcReg is guarateed to be the register whose live interval that is
1810 li_->removeInterval(SrcReg);
1812 // Update regalloc hint.
1813 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1815 // Manually deleted the live interval copy.
1821 // If resulting interval has a preference that no longer fits because of subreg
1822 // coalescing, just clear the preference.
1823 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1824 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1825 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1826 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1827 if (!RC->contains(Preference))
1828 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1832 dbgs() << "\t\tJoined. Result = ";
1833 ResDstInt->print(dbgs(), tri_);
1841 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1842 /// compute what the resultant value numbers for each value in the input two
1843 /// ranges will be. This is complicated by copies between the two which can
1844 /// and will commonly cause multiple value numbers to be merged into one.
1846 /// VN is the value number that we're trying to resolve. InstDefiningValue
1847 /// keeps track of the new InstDefiningValue assignment for the result
1848 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1849 /// whether a value in this or other is a copy from the opposite set.
1850 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1851 /// already been assigned.
1853 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1854 /// contains the value number the copy is from.
1856 static unsigned ComputeUltimateVN(VNInfo *VNI,
1857 SmallVector<VNInfo*, 16> &NewVNInfo,
1858 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1859 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1860 SmallVector<int, 16> &ThisValNoAssignments,
1861 SmallVector<int, 16> &OtherValNoAssignments) {
1862 unsigned VN = VNI->id;
1864 // If the VN has already been computed, just return it.
1865 if (ThisValNoAssignments[VN] >= 0)
1866 return ThisValNoAssignments[VN];
1867 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1869 // If this val is not a copy from the other val, then it must be a new value
1870 // number in the destination.
1871 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1872 if (I == ThisFromOther.end()) {
1873 NewVNInfo.push_back(VNI);
1874 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1876 VNInfo *OtherValNo = I->second;
1878 // Otherwise, this *is* a copy from the RHS. If the other side has already
1879 // been computed, return it.
1880 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1881 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1883 // Mark this value number as currently being computed, then ask what the
1884 // ultimate value # of the other value is.
1885 ThisValNoAssignments[VN] = -2;
1886 unsigned UltimateVN =
1887 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1888 OtherValNoAssignments, ThisValNoAssignments);
1889 return ThisValNoAssignments[VN] = UltimateVN;
1892 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1893 return std::find(V.begin(), V.end(), Val) != V.end();
1896 static bool isValNoDefMove(const MachineInstr *MI, unsigned DR, unsigned SR,
1897 const TargetInstrInfo *TII,
1898 const TargetRegisterInfo *TRI) {
1899 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1900 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1902 else if (MI->isExtractSubreg()) {
1903 DstReg = MI->getOperand(0).getReg();
1904 SrcReg = MI->getOperand(1).getReg();
1905 } else if (MI->isSubregToReg() ||
1906 MI->isInsertSubreg()) {
1907 DstReg = MI->getOperand(0).getReg();
1908 SrcReg = MI->getOperand(2).getReg();
1911 return (SrcReg == SR || TRI->isSuperRegister(SR, SrcReg)) &&
1912 (DstReg == DR || TRI->isSuperRegister(DR, DstReg));
1915 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1916 /// the specified live interval is defined by a copy from the specified
1918 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1921 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1924 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1925 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1926 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1927 *tri_->getSuperRegisters(li.reg)) {
1928 // It's a sub-register live interval, we may not have precise information.
1930 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1931 if (DefMI && isValNoDefMove(DefMI, li.reg, Reg, tii_, tri_)) {
1932 // Cache computed info.
1933 LR->valno->def = LR->start;
1934 LR->valno->setCopy(DefMI);
1942 /// ValueLiveAt - Return true if the LiveRange pointed to by the given
1943 /// iterator, or any subsequent range with the same value number,
1944 /// is live at the given point.
1945 bool SimpleRegisterCoalescing::ValueLiveAt(LiveInterval::iterator LRItr,
1946 LiveInterval::iterator LREnd,
1947 SlotIndex defPoint) const {
1948 for (const VNInfo *valno = LRItr->valno;
1949 (LRItr != LREnd) && (LRItr->valno == valno); ++LRItr) {
1950 if (LRItr->contains(defPoint))
1958 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1959 /// caller of this method must guarantee that the RHS only contains a single
1960 /// value number and that the RHS is not defined by a copy from this
1961 /// interval. This returns false if the intervals are not joinable, or it
1962 /// joins them and returns true.
1963 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1964 assert(RHS.containsOneValue());
1966 // Some number (potentially more than one) value numbers in the current
1967 // interval may be defined as copies from the RHS. Scan the overlapping
1968 // portions of the LHS and RHS, keeping track of this and looking for
1969 // overlapping live ranges that are NOT defined as copies. If these exist, we
1972 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1973 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1975 if (LHSIt->start < RHSIt->start) {
1976 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1977 if (LHSIt != LHS.begin()) --LHSIt;
1978 } else if (RHSIt->start < LHSIt->start) {
1979 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1980 if (RHSIt != RHS.begin()) --RHSIt;
1983 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1986 // Determine if these live intervals overlap.
1987 bool Overlaps = false;
1988 if (LHSIt->start <= RHSIt->start)
1989 Overlaps = LHSIt->end > RHSIt->start;
1991 Overlaps = RHSIt->end > LHSIt->start;
1993 // If the live intervals overlap, there are two interesting cases: if the
1994 // LHS interval is defined by a copy from the RHS, it's ok and we record
1995 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1996 // coalesce these live ranges and we bail out.
1998 // If we haven't already recorded that this value # is safe, check it.
1999 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
2000 // If it's re-defined by an early clobber somewhere in the live range,
2001 // then conservatively abort coalescing.
2002 if (LHSIt->valno->hasRedefByEC())
2004 // Copy from the RHS?
2005 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
2006 return false; // Nope, bail out.
2008 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2009 // Here is an interesting situation:
2011 // vr1025 = copy vr1024
2016 // Even though vr1025 is copied from vr1024, it's not safe to
2017 // coalesce them since the live range of vr1025 intersects the
2018 // def of vr1024. This happens because vr1025 is assigned the
2019 // value of the previous iteration of vr1024.
2021 EliminatedLHSVals.push_back(LHSIt->valno);
2024 // We know this entire LHS live range is okay, so skip it now.
2025 if (++LHSIt == LHSEnd) break;
2029 if (LHSIt->end < RHSIt->end) {
2030 if (++LHSIt == LHSEnd) break;
2032 // One interesting case to check here. It's possible that we have
2033 // something like "X3 = Y" which defines a new value number in the LHS,
2034 // and is the last use of this liverange of the RHS. In this case, we
2035 // want to notice this copy (so that it gets coalesced away) even though
2036 // the live ranges don't actually overlap.
2037 if (LHSIt->start == RHSIt->end) {
2038 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
2039 // We already know that this value number is going to be merged in
2040 // if coalescing succeeds. Just skip the liverange.
2041 if (++LHSIt == LHSEnd) break;
2043 // If it's re-defined by an early clobber somewhere in the live range,
2044 // then conservatively abort coalescing.
2045 if (LHSIt->valno->hasRedefByEC())
2047 // Otherwise, if this is a copy from the RHS, mark it as being merged
2049 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
2050 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2051 // Here is an interesting situation:
2053 // vr1025 = copy vr1024
2058 // Even though vr1025 is copied from vr1024, it's not safe to
2059 // coalesced them since live range of vr1025 intersects the
2060 // def of vr1024. This happens because vr1025 is assigned the
2061 // value of the previous iteration of vr1024.
2063 EliminatedLHSVals.push_back(LHSIt->valno);
2065 // We know this entire LHS live range is okay, so skip it now.
2066 if (++LHSIt == LHSEnd) break;
2071 if (++RHSIt == RHSEnd) break;
2075 // If we got here, we know that the coalescing will be successful and that
2076 // the value numbers in EliminatedLHSVals will all be merged together. Since
2077 // the most common case is that EliminatedLHSVals has a single number, we
2078 // optimize for it: if there is more than one value, we merge them all into
2079 // the lowest numbered one, then handle the interval as if we were merging
2080 // with one value number.
2081 VNInfo *LHSValNo = NULL;
2082 if (EliminatedLHSVals.size() > 1) {
2083 // Loop through all the equal value numbers merging them into the smallest
2085 VNInfo *Smallest = EliminatedLHSVals[0];
2086 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
2087 if (EliminatedLHSVals[i]->id < Smallest->id) {
2088 // Merge the current notion of the smallest into the smaller one.
2089 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2090 Smallest = EliminatedLHSVals[i];
2092 // Merge into the smallest.
2093 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2096 LHSValNo = Smallest;
2097 } else if (EliminatedLHSVals.empty()) {
2098 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2099 *tri_->getSuperRegisters(LHS.reg))
2100 // Imprecise sub-register information. Can't handle it.
2102 llvm_unreachable("No copies from the RHS?");
2104 LHSValNo = EliminatedLHSVals[0];
2107 // Okay, now that there is a single LHS value number that we're merging the
2108 // RHS into, update the value number info for the LHS to indicate that the
2109 // value number is defined where the RHS value number was.
2110 const VNInfo *VNI = RHS.getValNumInfo(0);
2111 LHSValNo->def = VNI->def;
2112 LHSValNo->setCopy(VNI->getCopy());
2114 // Okay, the final step is to loop over the RHS live intervals, adding them to
2116 if (VNI->hasPHIKill())
2117 LHSValNo->setHasPHIKill(true);
2118 LHS.addKills(LHSValNo, VNI->kills);
2119 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2121 LHS.ComputeJoinedWeight(RHS);
2123 // Update regalloc hint if both are virtual registers.
2124 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2125 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2126 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2127 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2128 if (RHSPref != LHSPref)
2129 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2132 // Update the liveintervals of sub-registers.
2133 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2134 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2135 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, LHS,
2136 li_->getVNInfoAllocator());
2141 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2142 /// returns false. Otherwise, if one of the intervals being joined is a
2143 /// physreg, this method always canonicalizes LHS to be it. The output
2144 /// "RHS" will not have been modified, so we can use this information
2145 /// below to update aliases.
2147 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2149 // Compute the final value assignment, assuming that the live ranges can be
2151 SmallVector<int, 16> LHSValNoAssignments;
2152 SmallVector<int, 16> RHSValNoAssignments;
2153 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2154 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2155 SmallVector<VNInfo*, 16> NewVNInfo;
2157 // If a live interval is a physical register, conservatively check if any
2158 // of its sub-registers is overlapping the live interval of the virtual
2159 // register. If so, do not coalesce.
2160 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2161 *tri_->getSubRegisters(LHS.reg)) {
2162 // If it's coalescing a virtual register to a physical register, estimate
2163 // its live interval length. This is the *cost* of scanning an entire live
2164 // interval. If the cost is low, we'll do an exhaustive check instead.
2166 // If this is something like this:
2174 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2175 // less conservative check. It's possible a sub-register is defined before
2176 // v1024 (or live in) and live out of BB1.
2177 if (RHS.containsOneValue() &&
2178 li_->intervalIsInOneMBB(RHS) &&
2179 li_->getApproximateInstructionCount(RHS) <= 10) {
2180 // Perform a more exhaustive check for some common cases.
2181 if (li_->conflictsWithSubPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2184 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2185 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2187 dbgs() << "\tInterfere with sub-register ";
2188 li_->getInterval(*SR).print(dbgs(), tri_);
2193 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2194 *tri_->getSubRegisters(RHS.reg)) {
2195 if (LHS.containsOneValue() &&
2196 li_->getApproximateInstructionCount(LHS) <= 10) {
2197 // Perform a more exhaustive check for some common cases.
2198 if (li_->conflictsWithSubPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2201 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2202 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2204 dbgs() << "\tInterfere with sub-register ";
2205 li_->getInterval(*SR).print(dbgs(), tri_);
2212 // Compute ultimate value numbers for the LHS and RHS values.
2213 if (RHS.containsOneValue()) {
2214 // Copies from a liveinterval with a single value are simple to handle and
2215 // very common, handle the special case here. This is important, because
2216 // often RHS is small and LHS is large (e.g. a physreg).
2218 // Find out if the RHS is defined as a copy from some value in the LHS.
2219 int RHSVal0DefinedFromLHS = -1;
2221 VNInfo *RHSValNoInfo = NULL;
2222 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2223 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2224 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2225 // If RHS is not defined as a copy from the LHS, we can use simpler and
2226 // faster checks to see if the live ranges are coalescable. This joiner
2227 // can't swap the LHS/RHS intervals though.
2228 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2229 return SimpleJoin(LHS, RHS);
2231 RHSValNoInfo = RHSValNoInfo0;
2234 // It was defined as a copy from the LHS, find out what value # it is.
2236 LHS.getLiveRangeContaining(RHSValNoInfo0->def.getPrevSlot())->valno;
2237 RHSValID = RHSValNoInfo->id;
2238 RHSVal0DefinedFromLHS = RHSValID;
2241 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2242 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2243 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2245 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2246 // should now get updated.
2247 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2250 unsigned VN = VNI->id;
2251 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2252 if (LHSSrcReg != RHS.reg) {
2253 // If this is not a copy from the RHS, its value number will be
2254 // unmodified by the coalescing.
2255 NewVNInfo[VN] = VNI;
2256 LHSValNoAssignments[VN] = VN;
2257 } else if (RHSValID == -1) {
2258 // Otherwise, it is a copy from the RHS, and we don't already have a
2259 // value# for it. Keep the current value number, but remember it.
2260 LHSValNoAssignments[VN] = RHSValID = VN;
2261 NewVNInfo[VN] = RHSValNoInfo;
2262 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2264 // Otherwise, use the specified value #.
2265 LHSValNoAssignments[VN] = RHSValID;
2266 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2267 NewVNInfo[VN] = RHSValNoInfo;
2268 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2272 NewVNInfo[VN] = VNI;
2273 LHSValNoAssignments[VN] = VN;
2277 assert(RHSValID != -1 && "Didn't find value #?");
2278 RHSValNoAssignments[0] = RHSValID;
2279 if (RHSVal0DefinedFromLHS != -1) {
2280 // This path doesn't go through ComputeUltimateVN so just set
2282 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2285 // Loop over the value numbers of the LHS, seeing if any are defined from
2287 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2290 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2293 // DstReg is known to be a register in the LHS interval. If the src is
2294 // from the RHS interval, we can use its value #.
2295 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2298 // Figure out the value # from the RHS.
2299 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2300 assert(lr && "Cannot find live range");
2301 LHSValsDefinedFromRHS[VNI] = lr->valno;
2304 // Loop over the value numbers of the RHS, seeing if any are defined from
2306 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2309 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2312 // DstReg is known to be a register in the RHS interval. If the src is
2313 // from the LHS interval, we can use its value #.
2314 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2317 // Figure out the value # from the LHS.
2318 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2319 assert(lr && "Cannot find live range");
2320 RHSValsDefinedFromLHS[VNI] = lr->valno;
2323 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2324 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2325 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2327 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2330 unsigned VN = VNI->id;
2331 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2333 ComputeUltimateVN(VNI, NewVNInfo,
2334 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2335 LHSValNoAssignments, RHSValNoAssignments);
2337 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2340 unsigned VN = VNI->id;
2341 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2343 // If this value number isn't a copy from the LHS, it's a new number.
2344 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2345 NewVNInfo.push_back(VNI);
2346 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2350 ComputeUltimateVN(VNI, NewVNInfo,
2351 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2352 RHSValNoAssignments, LHSValNoAssignments);
2356 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2357 // interval lists to see if these intervals are coalescable.
2358 LiveInterval::const_iterator I = LHS.begin();
2359 LiveInterval::const_iterator IE = LHS.end();
2360 LiveInterval::const_iterator J = RHS.begin();
2361 LiveInterval::const_iterator JE = RHS.end();
2363 // Skip ahead until the first place of potential sharing.
2364 if (I->start < J->start) {
2365 I = std::upper_bound(I, IE, J->start);
2366 if (I != LHS.begin()) --I;
2367 } else if (J->start < I->start) {
2368 J = std::upper_bound(J, JE, I->start);
2369 if (J != RHS.begin()) --J;
2373 // Determine if these two live ranges overlap.
2375 if (I->start < J->start) {
2376 Overlaps = I->end > J->start;
2378 Overlaps = J->end > I->start;
2381 // If so, check value # info to determine if they are really different.
2383 // If the live range overlap will map to the same value number in the
2384 // result liverange, we can still coalesce them. If not, we can't.
2385 if (LHSValNoAssignments[I->valno->id] !=
2386 RHSValNoAssignments[J->valno->id])
2388 // If it's re-defined by an early clobber somewhere in the live range,
2389 // then conservatively abort coalescing.
2390 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
2394 if (I->end < J->end) {
2403 // Update kill info. Some live ranges are extended due to copy coalescing.
2404 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2405 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2406 VNInfo *VNI = I->first;
2407 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2408 NewVNInfo[LHSValID]->removeKill(VNI->def);
2409 if (VNI->hasPHIKill())
2410 NewVNInfo[LHSValID]->setHasPHIKill(true);
2411 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2414 // Update kill info. Some live ranges are extended due to copy coalescing.
2415 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2416 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2417 VNInfo *VNI = I->first;
2418 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2419 NewVNInfo[RHSValID]->removeKill(VNI->def);
2420 if (VNI->hasPHIKill())
2421 NewVNInfo[RHSValID]->setHasPHIKill(true);
2422 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2425 // If we get here, we know that we can coalesce the live ranges. Ask the
2426 // intervals to coalesce themselves now.
2427 if ((RHS.ranges.size() > LHS.ranges.size() &&
2428 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2429 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2430 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2434 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2442 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2443 // depth of the basic block (the unsigned), and then on the MBB number.
2444 struct DepthMBBCompare {
2445 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2446 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2447 // Deeper loops first
2448 if (LHS.first != RHS.first)
2449 return LHS.first > RHS.first;
2451 // Prefer blocks that are more connected in the CFG. This takes care of
2452 // the most difficult copies first while intervals are short.
2453 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
2454 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
2458 // As a last resort, sort by block number.
2459 return LHS.second->getNumber() < RHS.second->getNumber();
2464 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2465 std::vector<CopyRec> &TryAgain) {
2466 DEBUG(dbgs() << MBB->getName() << ":\n");
2468 std::vector<CopyRec> VirtCopies;
2469 std::vector<CopyRec> PhysCopies;
2470 std::vector<CopyRec> ImpDefCopies;
2471 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2473 MachineInstr *Inst = MII++;
2475 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2476 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2477 bool isInsUndef = false;
2478 if (Inst->isExtractSubreg()) {
2479 DstReg = Inst->getOperand(0).getReg();
2480 SrcReg = Inst->getOperand(1).getReg();
2481 } else if (Inst->isInsertSubreg()) {
2482 DstReg = Inst->getOperand(0).getReg();
2483 SrcReg = Inst->getOperand(2).getReg();
2484 if (Inst->getOperand(1).isUndef())
2486 } else if (Inst->isInsertSubreg() || Inst->isSubregToReg()) {
2487 DstReg = Inst->getOperand(0).getReg();
2488 SrcReg = Inst->getOperand(2).getReg();
2489 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2492 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2493 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2495 (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
2496 ImpDefCopies.push_back(CopyRec(Inst, 0));
2497 else if (SrcIsPhys || DstIsPhys)
2498 PhysCopies.push_back(CopyRec(Inst, 0));
2500 VirtCopies.push_back(CopyRec(Inst, 0));
2503 // Try coalescing implicit copies and insert_subreg <undef> first,
2504 // followed by copies to / from physical registers, then finally copies
2505 // from virtual registers to virtual registers.
2506 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2507 CopyRec &TheCopy = ImpDefCopies[i];
2509 if (!JoinCopy(TheCopy, Again))
2511 TryAgain.push_back(TheCopy);
2513 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2514 CopyRec &TheCopy = PhysCopies[i];
2516 if (!JoinCopy(TheCopy, Again))
2518 TryAgain.push_back(TheCopy);
2520 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2521 CopyRec &TheCopy = VirtCopies[i];
2523 if (!JoinCopy(TheCopy, Again))
2525 TryAgain.push_back(TheCopy);
2529 void SimpleRegisterCoalescing::joinIntervals() {
2530 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2532 std::vector<CopyRec> TryAgainList;
2533 if (loopInfo->empty()) {
2534 // If there are no loops in the function, join intervals in function order.
2535 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2537 CopyCoalesceInMBB(I, TryAgainList);
2539 // Otherwise, join intervals in inner loops before other intervals.
2540 // Unfortunately we can't just iterate over loop hierarchy here because
2541 // there may be more MBB's than BB's. Collect MBB's for sorting.
2543 // Join intervals in the function prolog first. We want to join physical
2544 // registers with virtual registers before the intervals got too long.
2545 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2546 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2547 MachineBasicBlock *MBB = I;
2548 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2551 // Sort by loop depth.
2552 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2554 // Finally, join intervals in loop nest order.
2555 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2556 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2559 // Joining intervals can allow other intervals to be joined. Iteratively join
2560 // until we make no progress.
2561 bool ProgressMade = true;
2562 while (ProgressMade) {
2563 ProgressMade = false;
2565 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2566 CopyRec &TheCopy = TryAgainList[i];
2571 bool Success = JoinCopy(TheCopy, Again);
2572 if (Success || !Again) {
2573 TheCopy.MI = 0; // Mark this one as done.
2574 ProgressMade = true;
2580 /// Return true if the two specified registers belong to different register
2581 /// classes. The registers may be either phys or virt regs.
2583 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2584 unsigned RegB) const {
2585 // Get the register classes for the first reg.
2586 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2587 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2588 "Shouldn't consider two physregs!");
2589 return !mri_->getRegClass(RegB)->contains(RegA);
2592 // Compare against the regclass for the second reg.
2593 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2594 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2595 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2596 return RegClassA != RegClassB;
2598 return !RegClassA->contains(RegB);
2601 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
2602 /// between cycles Start and End or NULL if there are no uses.
2604 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
2607 SlotIndex &UseIdx) const{
2608 UseIdx = SlotIndex();
2609 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2610 MachineOperand *LastUse = NULL;
2611 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
2612 E = mri_->use_nodbg_end(); I != E; ++I) {
2613 MachineOperand &Use = I.getOperand();
2614 MachineInstr *UseMI = Use.getParent();
2615 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2616 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2618 // Ignore identity copies.
2620 SlotIndex Idx = li_->getInstructionIndex(UseMI);
2621 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
2622 // that compares higher than any other interval.
2623 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2625 UseIdx = Idx.getUseIndex();
2631 SlotIndex s = Start;
2632 SlotIndex e = End.getPrevSlot().getBaseIndex();
2634 // Skip deleted instructions
2635 MachineInstr *MI = li_->getInstructionFromIndex(e);
2636 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
2637 e = e.getPrevIndex();
2638 MI = li_->getInstructionFromIndex(e);
2640 if (e < s || MI == NULL)
2643 // Ignore identity copies.
2644 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2645 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2647 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2648 MachineOperand &Use = MI->getOperand(i);
2649 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2650 tri_->regsOverlap(Use.getReg(), Reg)) {
2651 UseIdx = e.getUseIndex();
2656 e = e.getPrevIndex();
2662 void SimpleRegisterCoalescing::releaseMemory() {
2663 JoinedCopies.clear();
2664 ReMatCopies.clear();
2668 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2670 mri_ = &fn.getRegInfo();
2671 tm_ = &fn.getTarget();
2672 tri_ = tm_->getRegisterInfo();
2673 tii_ = tm_->getInstrInfo();
2674 li_ = &getAnalysis<LiveIntervals>();
2675 AA = &getAnalysis<AliasAnalysis>();
2676 loopInfo = &getAnalysis<MachineLoopInfo>();
2678 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2679 << "********** Function: "
2680 << ((Value*)mf_->getFunction())->getName() << '\n');
2682 allocatableRegs_ = tri_->getAllocatableSet(fn);
2683 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2684 E = tri_->regclass_end(); I != E; ++I)
2685 allocatableRCRegs_.insert(std::make_pair(*I,
2686 tri_->getAllocatableSet(fn, *I)));
2688 // Join (coalesce) intervals if requested.
2689 if (EnableJoining) {
2692 dbgs() << "********** INTERVALS POST JOINING **********\n";
2693 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
2695 I->second->print(dbgs(), tri_);
2701 // Perform a final pass over the instructions and compute spill weights
2702 // and remove identity moves.
2703 SmallVector<unsigned, 4> DeadDefs;
2704 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2705 mbbi != mbbe; ++mbbi) {
2706 MachineBasicBlock* mbb = mbbi;
2707 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2709 MachineInstr *MI = mii;
2710 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2711 if (JoinedCopies.count(MI)) {
2712 // Delete all coalesced copies.
2713 bool DoDelete = true;
2714 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2715 assert((MI->isExtractSubreg() || MI->isInsertSubreg() ||
2716 MI->isSubregToReg()) && "Unrecognized copy instruction");
2717 DstReg = MI->getOperand(0).getReg();
2718 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2719 // Do not delete extract_subreg, insert_subreg of physical
2720 // registers unless the definition is dead. e.g.
2721 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2722 // or else the scavenger may complain. LowerSubregs will
2723 // delete them later.
2726 if (MI->allDefsAreDead()) {
2727 LiveInterval &li = li_->getInterval(DstReg);
2728 if (!ShortenDeadCopySrcLiveRange(li, MI))
2729 ShortenDeadCopyLiveRange(li, MI);
2733 mii = llvm::next(mii);
2735 li_->RemoveMachineInstrFromMaps(MI);
2736 mii = mbbi->erase(mii);
2742 // Now check if this is a remat'ed def instruction which is now dead.
2743 if (ReMatDefs.count(MI)) {
2745 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2746 const MachineOperand &MO = MI->getOperand(i);
2749 unsigned Reg = MO.getReg();
2752 if (TargetRegisterInfo::isVirtualRegister(Reg))
2753 DeadDefs.push_back(Reg);
2756 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2757 !mri_->use_nodbg_empty(Reg)) {
2763 while (!DeadDefs.empty()) {
2764 unsigned DeadDef = DeadDefs.back();
2765 DeadDefs.pop_back();
2766 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2768 li_->RemoveMachineInstrFromMaps(mii);
2769 mii = mbbi->erase(mii);
2775 // If the move will be an identity move delete it
2776 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2777 if (isMove && SrcReg == DstReg) {
2778 if (li_->hasInterval(SrcReg)) {
2779 LiveInterval &RegInt = li_->getInterval(SrcReg);
2780 // If def of this move instruction is dead, remove its live range
2781 // from the dstination register's live interval.
2782 if (MI->registerDefIsDead(DstReg)) {
2783 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2784 ShortenDeadCopyLiveRange(RegInt, MI);
2787 li_->RemoveMachineInstrFromMaps(MI);
2788 mii = mbbi->erase(mii);
2795 // Check for now unnecessary kill flags.
2796 if (li_->isNotInMIMap(MI)) continue;
2797 SlotIndex UseIdx = li_->getInstructionIndex(MI).getUseIndex();
2798 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2799 MachineOperand &MO = MI->getOperand(i);
2800 if (!MO.isReg() || !MO.isKill()) continue;
2801 unsigned reg = MO.getReg();
2802 if (!reg || !li_->hasInterval(reg)) continue;
2803 LiveInterval &LI = li_->getInterval(reg);
2804 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
2806 (!LR->valno->isKill(UseIdx.getDefIndex()) &&
2807 LR->valno->def != UseIdx.getDefIndex()))
2808 MO.setIsKill(false);
2817 /// print - Implement the dump method.
2818 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2822 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2823 return new SimpleRegisterCoalescing();
2826 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2827 DEFINING_FILE_FOR(SimpleRegisterCoalescing)