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/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
41 STATISTIC(numJoins , "Number of interval joins performed");
42 STATISTIC(numCrossRCs , "Number of cross class joins performed");
43 STATISTIC(numCommutes , "Number of instruction commuting performed");
44 STATISTIC(numExtends , "Number of copies extended");
45 STATISTIC(NumReMats , "Number of instructions re-materialized");
46 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
47 STATISTIC(numAborts , "Number of times interval joining aborted");
48 STATISTIC(numDeadValNo, "Number of valno def marked dead");
50 char SimpleRegisterCoalescing::ID = 0;
52 EnableJoining("join-liveintervals",
53 cl::desc("Coalesce copies (default=true)"),
57 DisableCrossClassJoin("disable-cross-class-join",
58 cl::desc("Avoid coalescing cross register class copies"),
59 cl::init(false), cl::Hidden);
62 PhysJoinTweak("tweak-phys-join-heuristics",
63 cl::desc("Tweak heuristics for joining phys reg with vr"),
64 cl::init(false), cl::Hidden);
66 static RegisterPass<SimpleRegisterCoalescing>
67 X("simple-register-coalescing", "Simple Register Coalescing");
69 // Declare that we implement the RegisterCoalescer interface
70 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
72 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
74 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<AliasAnalysis>();
77 AU.addRequired<LiveIntervals>();
78 AU.addPreserved<LiveIntervals>();
79 AU.addPreserved<SlotIndexes>();
80 AU.addRequired<MachineLoopInfo>();
81 AU.addPreserved<MachineLoopInfo>();
82 AU.addPreservedID(MachineDominatorsID);
84 AU.addPreservedID(StrongPHIEliminationID);
86 AU.addPreservedID(PHIEliminationID);
87 AU.addPreservedID(TwoAddressInstructionPassID);
88 MachineFunctionPass::getAnalysisUsage(AU);
91 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
92 /// being the source and IntB being the dest, thus this defines a value number
93 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
94 /// see if we can merge these two pieces of B into a single value number,
95 /// eliminating a copy. For example:
99 /// B1 = A3 <- this copy
101 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
102 /// value number to be replaced with B0 (which simplifies the B liveinterval).
104 /// This returns true if an interval was modified.
106 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
108 MachineInstr *CopyMI) {
109 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
111 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
112 // the example above.
113 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
114 assert(BLR != IntB.end() && "Live range not found!");
115 VNInfo *BValNo = BLR->valno;
117 // Get the location that B is defined at. Two options: either this value has
118 // an unknown definition point or it is defined at CopyIdx. If unknown, we
120 if (!BValNo->getCopy()) return false;
121 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
123 // AValNo is the value number in A that defines the copy, A3 in the example.
124 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
125 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
126 assert(ALR != IntA.end() && "Live range not found!");
127 VNInfo *AValNo = ALR->valno;
128 // If it's re-defined by an early clobber somewhere in the live range, then
129 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
131 // 172 %ECX<def> = MOV32rr %reg1039<kill>
132 // 180 INLINEASM <es:subl $5,$1
133 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
134 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
135 // 188 %EAX<def> = MOV32rr %EAX<kill>
136 // 196 %ECX<def> = MOV32rr %ECX<kill>
137 // 204 %ECX<def> = MOV32rr %ECX<kill>
138 // 212 %EAX<def> = MOV32rr %EAX<kill>
139 // 220 %EAX<def> = MOV32rr %EAX
140 // 228 %reg1039<def> = MOV32rr %ECX<kill>
141 // The early clobber operand ties ECX input to the ECX def.
143 // The live interval of ECX is represented as this:
144 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
145 // The coalescer has no idea there was a def in the middle of [174,230].
146 if (AValNo->hasRedefByEC())
149 // If AValNo is defined as a copy from IntB, we can potentially process this.
150 // Get the instruction that defines this value number.
151 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
152 if (!SrcReg) return false; // Not defined by a copy.
154 // If the value number is not defined by a copy instruction, ignore it.
156 // If the source register comes from an interval other than IntB, we can't
158 if (SrcReg != IntB.reg) return false;
160 // Get the LiveRange in IntB that this value number starts with.
161 LiveInterval::iterator ValLR =
162 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
163 assert(ValLR != IntB.end() && "Live range not found!");
165 // Make sure that the end of the live range is inside the same block as
167 MachineInstr *ValLREndInst =
168 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
170 ValLREndInst->getParent() != CopyMI->getParent()) return false;
172 // Okay, we now know that ValLR ends in the same block that the CopyMI
173 // live-range starts. If there are no intervening live ranges between them in
174 // IntB, we can merge them.
175 if (ValLR+1 != BLR) return false;
177 // If a live interval is a physical register, conservatively check if any
178 // of its sub-registers is overlapping the live interval of the virtual
179 // register. If so, do not coalesce.
180 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
181 *tri_->getSubRegisters(IntB.reg)) {
182 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
183 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
185 errs() << "Interfere with sub-register ";
186 li_->getInterval(*SR).print(errs(), tri_);
193 errs() << "\nExtending: ";
194 IntB.print(errs(), tri_);
197 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
198 // We are about to delete CopyMI, so need to remove it as the 'instruction
199 // that defines this value #'. Update the the valnum with the new defining
201 BValNo->def = FillerStart;
204 // Okay, we can merge them. We need to insert a new liverange:
205 // [ValLR.end, BLR.begin) of either value number, then we merge the
206 // two value numbers.
207 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
209 // If the IntB live range is assigned to a physical register, and if that
210 // physreg has sub-registers, update their live intervals as well.
211 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
212 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
213 LiveInterval &SRLI = li_->getInterval(*SR);
214 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
215 SRLI.getNextValue(FillerStart, 0, true,
216 li_->getVNInfoAllocator())));
220 // Okay, merge "B1" into the same value number as "B0".
221 if (BValNo != ValLR->valno) {
222 IntB.addKills(ValLR->valno, BValNo->kills);
223 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
226 errs() << " result = ";
227 IntB.print(errs(), tri_);
231 // If the source instruction was killing the source register before the
232 // merge, unset the isKill marker given the live range has been extended.
233 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
235 ValLREndInst->getOperand(UIdx).setIsKill(false);
236 ValLR->valno->removeKill(FillerStart);
239 // If the copy instruction was killing the destination register before the
240 // merge, find the last use and trim the live range. That will also add the
242 if (CopyMI->killsRegister(IntA.reg))
243 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
249 /// HasOtherReachingDefs - Return true if there are definitions of IntB
250 /// other than BValNo val# that can reach uses of AValno val# of IntA.
251 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
255 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
257 if (AI->valno != AValNo) continue;
258 LiveInterval::Ranges::iterator BI =
259 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
260 if (BI != IntB.ranges.begin())
262 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
263 if (BI->valno == BValNo)
265 if (BI->start <= AI->start && BI->end > AI->start)
267 if (BI->start > AI->start && BI->start < AI->end)
275 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
276 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
278 MachineOperand &MO = MI->getOperand(i);
279 if (MO.isReg() && MO.isImplicit())
280 NewMI->addOperand(MO);
284 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
285 /// being the source and IntB being the dest, thus this defines a value number
286 /// in IntB. If the source value number (in IntA) is defined by a commutable
287 /// instruction and its other operand is coalesced to the copy dest register,
288 /// see if we can transform the copy into a noop by commuting the definition. For
291 /// A3 = op A2 B0<kill>
293 /// B1 = A3 <- this copy
295 /// = op A3 <- more uses
299 /// B2 = op B0 A2<kill>
301 /// B1 = B2 <- now an identify copy
303 /// = op B2 <- more uses
305 /// This returns true if an interval was modified.
307 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
309 MachineInstr *CopyMI) {
311 li_->getInstructionIndex(CopyMI).getDefIndex();
313 // FIXME: For now, only eliminate the copy by commuting its def when the
314 // source register is a virtual register. We want to guard against cases
315 // where the copy is a back edge copy and commuting the def lengthen the
316 // live interval of the source register to the entire loop.
317 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
320 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
321 // the example above.
322 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
323 assert(BLR != IntB.end() && "Live range not found!");
324 VNInfo *BValNo = BLR->valno;
326 // Get the location that B is defined at. Two options: either this value has
327 // an unknown definition point or it is defined at CopyIdx. If unknown, we
329 if (!BValNo->getCopy()) return false;
330 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
332 // AValNo is the value number in A that defines the copy, A3 in the example.
333 LiveInterval::iterator ALR =
334 IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); //
336 assert(ALR != IntA.end() && "Live range not found!");
337 VNInfo *AValNo = ALR->valno;
338 // If other defs can reach uses of this def, then it's not safe to perform
339 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
341 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
342 AValNo->isUnused() || AValNo->hasPHIKill())
344 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
345 const TargetInstrDesc &TID = DefMI->getDesc();
346 if (!TID.isCommutable())
348 // If DefMI is a two-address instruction then commuting it will change the
349 // destination register.
350 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
351 assert(DefIdx != -1);
353 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
355 unsigned Op1, Op2, NewDstIdx;
356 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
360 else if (Op2 == UseOpIdx)
365 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
366 unsigned NewReg = NewDstMO.getReg();
367 if (NewReg != IntB.reg || !NewDstMO.isKill())
370 // Make sure there are no other definitions of IntB that would reach the
371 // uses which the new definition can reach.
372 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
375 // If some of the uses of IntA.reg is already coalesced away, return false.
376 // It's not possible to determine whether it's safe to perform the coalescing.
377 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
378 UE = mri_->use_end(); UI != UE; ++UI) {
379 MachineInstr *UseMI = &*UI;
380 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
381 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
382 if (ULR == IntA.end())
384 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
388 // At this point we have decided that it is legal to do this
389 // transformation. Start by commuting the instruction.
390 MachineBasicBlock *MBB = DefMI->getParent();
391 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
394 if (NewMI != DefMI) {
395 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
396 MBB->insert(DefMI, NewMI);
399 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
400 NewMI->getOperand(OpIdx).setIsKill();
402 bool BHasPHIKill = BValNo->hasPHIKill();
403 SmallVector<VNInfo*, 4> BDeadValNos;
404 VNInfo::KillSet BKills;
405 std::map<SlotIndex, SlotIndex> BExtend;
407 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
416 // then do not add kills of A to the newly created B interval.
417 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
419 BExtend[ALR->end] = BLR->end;
421 // Update uses of IntA of the specific Val# with IntB.
422 bool BHasSubRegs = false;
423 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
424 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
425 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
426 UE = mri_->use_end(); UI != UE;) {
427 MachineOperand &UseMO = UI.getOperand();
428 MachineInstr *UseMI = &*UI;
430 if (JoinedCopies.count(UseMI))
432 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
433 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
434 if (ULR == IntA.end() || ULR->valno != AValNo)
436 UseMO.setReg(NewReg);
439 if (UseMO.isKill()) {
441 UseMO.setIsKill(false);
443 BKills.push_back(UseIdx.getDefIndex());
445 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
446 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
448 if (DstReg == IntB.reg) {
449 // This copy will become a noop. If it's defining a new val#,
450 // remove that val# as well. However this live range is being
451 // extended to the end of the existing live range defined by the copy.
452 SlotIndex DefIdx = UseIdx.getDefIndex();
453 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
454 BHasPHIKill |= DLR->valno->hasPHIKill();
455 assert(DLR->valno->def == DefIdx);
456 BDeadValNos.push_back(DLR->valno);
457 BExtend[DLR->start] = DLR->end;
458 JoinedCopies.insert(UseMI);
459 // If this is a kill but it's going to be removed, the last use
460 // of the same val# is the new kill.
466 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
467 // simply extend BLR if CopyMI doesn't end the range.
469 errs() << "\nExtending: ";
470 IntB.print(errs(), tri_);
473 // Remove val#'s defined by copies that will be coalesced away.
474 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
475 VNInfo *DeadVNI = BDeadValNos[i];
477 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
478 LiveInterval &SRLI = li_->getInterval(*SR);
479 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
480 SRLI.removeValNo(SRLR->valno);
483 IntB.removeValNo(BDeadValNos[i]);
486 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
487 // is updated. Kills are also updated.
488 VNInfo *ValNo = BValNo;
489 ValNo->def = AValNo->def;
491 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
492 if (ValNo->kills[j] != BLR->end)
493 BKills.push_back(ValNo->kills[j]);
495 ValNo->kills.clear();
496 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
498 if (AI->valno != AValNo) continue;
499 SlotIndex End = AI->end;
500 std::map<SlotIndex, SlotIndex>::iterator
501 EI = BExtend.find(End);
502 if (EI != BExtend.end())
504 IntB.addRange(LiveRange(AI->start, End, ValNo));
506 // If the IntB live range is assigned to a physical register, and if that
507 // physreg has sub-registers, update their live intervals as well.
509 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
510 LiveInterval &SRLI = li_->getInterval(*SR);
511 SRLI.MergeInClobberRange(*li_, AI->start, End, li_->getVNInfoAllocator());
515 IntB.addKills(ValNo, BKills);
516 ValNo->setHasPHIKill(BHasPHIKill);
519 errs() << " result = ";
520 IntB.print(errs(), tri_);
522 errs() << "\nShortening: ";
523 IntA.print(errs(), tri_);
526 IntA.removeValNo(AValNo);
529 errs() << " result = ";
530 IntA.print(errs(), tri_);
538 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
539 /// fallthoughs to SuccMBB.
540 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
541 MachineBasicBlock *SuccMBB,
542 const TargetInstrInfo *tii_) {
545 MachineBasicBlock *TBB = 0, *FBB = 0;
546 SmallVector<MachineOperand, 4> Cond;
547 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
548 MBB->isSuccessor(SuccMBB);
551 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
552 /// from a physical register live interval as well as from the live intervals
553 /// of its sub-registers.
554 static void removeRange(LiveInterval &li,
555 SlotIndex Start, SlotIndex End,
556 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
557 li.removeRange(Start, End, true);
558 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
559 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
560 if (!li_->hasInterval(*SR))
562 LiveInterval &sli = li_->getInterval(*SR);
563 SlotIndex RemoveStart = Start;
564 SlotIndex RemoveEnd = Start;
566 while (RemoveEnd != End) {
567 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
570 RemoveEnd = (LR->end < End) ? LR->end : End;
571 sli.removeRange(RemoveStart, RemoveEnd, true);
572 RemoveStart = RemoveEnd;
578 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
579 /// as the copy instruction, trim the live interval to the last use and return
582 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
583 MachineBasicBlock *CopyMBB,
585 const LiveRange *LR) {
586 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
587 SlotIndex LastUseIdx;
588 MachineOperand *LastUse =
589 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
591 MachineInstr *LastUseMI = LastUse->getParent();
592 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
599 // r1025<dead> = r1024<kill>
600 if (MBBStart < LR->end)
601 removeRange(li, MBBStart, LR->end, li_, tri_);
605 // There are uses before the copy, just shorten the live range to the end
607 LastUse->setIsKill();
608 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
609 LR->valno->addKill(LastUseIdx.getDefIndex());
610 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
611 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
613 // Last use is itself an identity code.
614 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
615 LastUseMI->getOperand(DeadIdx).setIsDead();
621 if (LR->start <= MBBStart && LR->end > MBBStart) {
622 if (LR->start == li_->getZeroIndex()) {
623 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
624 // Live-in to the function but dead. Remove it from entry live-in set.
625 mf_->begin()->removeLiveIn(li.reg);
627 // FIXME: Shorten intervals in BBs that reaches this BB.
633 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
634 /// computation, replace the copy by rematerialize the definition.
635 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
638 MachineInstr *CopyMI) {
639 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
640 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
641 assert(SrcLR != SrcInt.end() && "Live range not found!");
642 VNInfo *ValNo = SrcLR->valno;
643 // If other defs can reach uses of this def, then it's not safe to perform
644 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
646 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
647 ValNo->isUnused() || ValNo->hasPHIKill())
649 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
650 const TargetInstrDesc &TID = DefMI->getDesc();
651 if (!TID.isAsCheapAsAMove())
653 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
655 bool SawStore = false;
656 if (!DefMI->isSafeToMove(tii_, SawStore, AA))
658 if (TID.getNumDefs() != 1)
660 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
661 // Make sure the copy destination register class fits the instruction
662 // definition register class. The mismatch can happen as a result of earlier
663 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
664 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
665 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
666 if (mri_->getRegClass(DstReg) != RC)
668 } else if (!RC->contains(DstReg))
672 // If destination register has a sub-register index on it, make sure it mtches
673 // the instruction register class.
675 const TargetInstrDesc &TID = DefMI->getDesc();
676 if (TID.getNumDefs() != 1)
678 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
679 const TargetRegisterClass *DstSubRC =
680 DstRC->getSubRegisterRegClass(DstSubIdx);
681 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
684 else if (DefRC != DstSubRC)
688 SlotIndex DefIdx = CopyIdx.getDefIndex();
689 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
690 DLR->valno->setCopy(0);
691 // Don't forget to update sub-register intervals.
692 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
693 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
694 if (!li_->hasInterval(*SR))
696 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
697 if (DLR && DLR->valno->getCopy() == CopyMI)
698 DLR->valno->setCopy(0);
702 // If copy kills the source register, find the last use and propagate
704 bool checkForDeadDef = false;
705 MachineBasicBlock *MBB = CopyMI->getParent();
706 if (CopyMI->killsRegister(SrcInt.reg))
707 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
708 checkForDeadDef = true;
711 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
712 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, tri_);
713 MachineInstr *NewMI = prior(MII);
715 if (checkForDeadDef) {
716 // PR4090 fix: Trim interval failed because there was no use of the
717 // source interval in this MBB. If the def is in this MBB too then we
718 // should mark it dead:
719 if (DefMI->getParent() == MBB) {
720 DefMI->addRegisterDead(SrcInt.reg, tri_);
721 SrcLR->end = SrcLR->start.getNextSlot();
725 // CopyMI may have implicit operands, transfer them over to the newly
726 // rematerialized instruction. And update implicit def interval valnos.
727 for (unsigned i = CopyMI->getDesc().getNumOperands(),
728 e = CopyMI->getNumOperands(); i != e; ++i) {
729 MachineOperand &MO = CopyMI->getOperand(i);
730 if (MO.isReg() && MO.isImplicit())
731 NewMI->addOperand(MO);
732 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
733 unsigned Reg = MO.getReg();
734 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
735 if (DLR && DLR->valno->getCopy() == CopyMI)
736 DLR->valno->setCopy(0);
740 TransferImplicitOps(CopyMI, NewMI);
741 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
742 CopyMI->eraseFromParent();
743 ReMatCopies.insert(CopyMI);
744 ReMatDefs.insert(DefMI);
749 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
750 /// update the subregister number if it is not zero. If DstReg is a
751 /// physical register and the existing subregister number of the def / use
752 /// being updated is not zero, make sure to set it to the correct physical
755 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
757 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
758 if (DstIsPhys && SubIdx) {
759 // Figure out the real physical register we are updating with.
760 DstReg = tri_->getSubReg(DstReg, SubIdx);
764 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
765 E = mri_->reg_end(); I != E; ) {
766 MachineOperand &O = I.getOperand();
767 MachineInstr *UseMI = &*I;
769 unsigned OldSubIdx = O.getSubReg();
771 unsigned UseDstReg = DstReg;
773 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
775 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
776 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
777 CopySrcSubIdx, CopyDstSubIdx) &&
778 CopySrcReg != CopyDstReg &&
779 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
780 // If the use is a copy and it won't be coalesced away, and its source
781 // is defined by a trivial computation, try to rematerialize it instead.
782 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
783 CopyDstSubIdx, UseMI))
792 // Sub-register indexes goes from small to large. e.g.
793 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
794 // EAX: 1 -> AL, 2 -> AX
795 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
796 // sub-register 2 is also AX.
797 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
798 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
801 // Remove would-be duplicated kill marker.
802 if (O.isKill() && UseMI->killsRegister(DstReg))
806 // After updating the operand, check if the machine instruction has
807 // become a copy. If so, update its val# information.
808 if (JoinedCopies.count(UseMI))
811 const TargetInstrDesc &TID = UseMI->getDesc();
812 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
813 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
814 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
815 CopySrcSubIdx, CopyDstSubIdx) &&
816 CopySrcReg != CopyDstReg &&
817 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
818 allocatableRegs_[CopyDstReg])) {
819 LiveInterval &LI = li_->getInterval(CopyDstReg);
821 li_->getInstructionIndex(UseMI).getDefIndex();
822 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
823 if (DLR->valno->def == DefIdx)
824 DLR->valno->setCopy(UseMI);
830 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
831 /// due to live range lengthening as the result of coalescing.
832 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
834 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
835 UE = mri_->use_end(); UI != UE; ++UI) {
836 MachineOperand &UseMO = UI.getOperand();
839 MachineInstr *UseMI = UseMO.getParent();
841 li_->getInstructionIndex(UseMI).getUseIndex();
842 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
844 (!LR->valno->isKill(UseIdx.getDefIndex()) &&
845 LR->valno->def != UseIdx.getDefIndex())) {
846 // Interesting problem. After coalescing reg1027's def and kill are both
847 // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814)
850 // 60 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
851 // 68 %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
852 // 76 t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
853 // 84 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
854 // 96 t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
856 // Do not remove the kill marker on t2LDRi12.
857 UseMO.setIsKill(false);
862 /// removeIntervalIfEmpty - Check if the live interval of a physical register
863 /// is empty, if so remove it and also remove the empty intervals of its
864 /// sub-registers. Return true if live interval is removed.
865 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
866 const TargetRegisterInfo *tri_) {
868 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
869 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
870 if (!li_->hasInterval(*SR))
872 LiveInterval &sli = li_->getInterval(*SR);
874 li_->removeInterval(*SR);
876 li_->removeInterval(li.reg);
882 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
883 /// Return true if live interval is removed.
884 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
885 MachineInstr *CopyMI) {
886 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
887 LiveInterval::iterator MLR =
888 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
890 return false; // Already removed by ShortenDeadCopySrcLiveRange.
891 SlotIndex RemoveStart = MLR->start;
892 SlotIndex RemoveEnd = MLR->end;
893 SlotIndex DefIdx = CopyIdx.getDefIndex();
894 // Remove the liverange that's defined by this.
895 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
896 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
897 return removeIntervalIfEmpty(li, li_, tri_);
902 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
903 /// the val# it defines. If the live interval becomes empty, remove it as well.
904 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
905 MachineInstr *DefMI) {
906 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
907 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
908 if (DefIdx != MLR->valno->def)
910 li.removeValNo(MLR->valno);
911 return removeIntervalIfEmpty(li, li_, tri_);
914 /// PropagateDeadness - Propagate the dead marker to the instruction which
915 /// defines the val#.
916 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
917 SlotIndex &LRStart, LiveIntervals *li_,
918 const TargetRegisterInfo* tri_) {
919 MachineInstr *DefMI =
920 li_->getInstructionFromIndex(LRStart.getDefIndex());
921 if (DefMI && DefMI != CopyMI) {
922 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
924 DefMI->getOperand(DeadIdx).setIsDead();
926 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
927 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
928 LRStart = LRStart.getNextSlot();
932 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
933 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
934 /// ends the live range there. If there isn't another use, then this live range
935 /// is dead. Return true if live interval is removed.
937 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
938 MachineInstr *CopyMI) {
939 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
940 if (CopyIdx == SlotIndex()) {
941 // FIXME: special case: function live in. It can be a general case if the
942 // first instruction index starts at > 0 value.
943 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
944 // Live-in to the function but dead. Remove it from entry live-in set.
945 if (mf_->begin()->isLiveIn(li.reg))
946 mf_->begin()->removeLiveIn(li.reg);
947 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
948 removeRange(li, LR->start, LR->end, li_, tri_);
949 return removeIntervalIfEmpty(li, li_, tri_);
952 LiveInterval::iterator LR =
953 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
955 // Livein but defined by a phi.
958 SlotIndex RemoveStart = LR->start;
959 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
960 if (LR->end > RemoveEnd)
961 // More uses past this copy? Nothing to do.
964 // If there is a last use in the same bb, we can't remove the live range.
965 // Shorten the live interval and return.
966 MachineBasicBlock *CopyMBB = CopyMI->getParent();
967 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
970 // There are other kills of the val#. Nothing to do.
971 if (!li.isOnlyLROfValNo(LR))
974 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
975 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
976 // If the live range starts in another mbb and the copy mbb is not a fall
977 // through mbb, then we can only cut the range from the beginning of the
979 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
981 if (LR->valno->def == RemoveStart) {
982 // If the def MI defines the val# and this copy is the only kill of the
983 // val#, then propagate the dead marker.
984 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
987 if (LR->valno->isKill(RemoveEnd))
988 LR->valno->removeKill(RemoveEnd);
991 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
992 return removeIntervalIfEmpty(li, li_, tri_);
995 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
996 /// from an implicit def to another register can be coalesced away.
997 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
999 LiveInterval &ImpLi) const{
1000 if (!CopyMI->killsRegister(ImpLi.reg))
1002 // Make sure this is the only use.
1003 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1004 UE = mri_->use_end(); UI != UE;) {
1005 MachineInstr *UseMI = &*UI;
1007 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1015 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1016 /// a virtual destination register with physical source register.
1018 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1019 MachineBasicBlock *CopyMBB,
1020 LiveInterval &DstInt,
1021 LiveInterval &SrcInt) {
1022 // If the virtual register live interval is long but it has low use desity,
1023 // do not join them, instead mark the physical register as its allocation
1025 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1026 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1027 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1028 if (Length > Threshold &&
1029 (((float)std::distance(mri_->use_begin(DstInt.reg),
1030 mri_->use_end()) / Length) < (1.0 / Threshold)))
1033 // If the virtual register live interval extends into a loop, turn down
1036 li_->getInstructionIndex(CopyMI).getDefIndex();
1037 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1039 // Let's see if the virtual register live interval extends into the loop.
1040 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1041 assert(DLR != DstInt.end() && "Live range not found!");
1042 DLR = DstInt.FindLiveRangeContaining(DLR->end.getNextSlot());
1043 if (DLR != DstInt.end()) {
1044 CopyMBB = li_->getMBBFromIndex(DLR->start);
1045 L = loopInfo->getLoopFor(CopyMBB);
1049 if (!L || Length <= Threshold)
1052 SlotIndex UseIdx = CopyIdx.getUseIndex();
1053 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1054 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1055 if (loopInfo->getLoopFor(SMBB) != L) {
1056 if (!loopInfo->isLoopHeader(CopyMBB))
1058 // If vr's live interval extends pass the loop header, do not join.
1059 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1060 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1061 MachineBasicBlock *SuccMBB = *SI;
1062 if (SuccMBB == CopyMBB)
1064 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1065 li_->getMBBEndIdx(SuccMBB).getNextIndex().getBaseIndex()))
1072 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1073 /// copy from a virtual source register to a physical destination register.
1075 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1076 MachineBasicBlock *CopyMBB,
1077 LiveInterval &DstInt,
1078 LiveInterval &SrcInt) {
1079 // If the virtual register live interval is long but it has low use desity,
1080 // do not join them, instead mark the physical register as its allocation
1082 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1083 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1084 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1085 if (Length > Threshold &&
1086 (((float)std::distance(mri_->use_begin(SrcInt.reg),
1087 mri_->use_end()) / Length) < (1.0 / Threshold)))
1091 // Must be implicit_def.
1094 // If the virtual register live interval is defined or cross a loop, turn
1095 // down aggressiveness.
1097 li_->getInstructionIndex(CopyMI).getDefIndex();
1098 SlotIndex UseIdx = CopyIdx.getUseIndex();
1099 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1100 assert(SLR != SrcInt.end() && "Live range not found!");
1101 SLR = SrcInt.FindLiveRangeContaining(SLR->start.getPrevSlot());
1102 if (SLR == SrcInt.end())
1104 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1105 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1107 if (!L || Length <= Threshold)
1110 if (loopInfo->getLoopFor(CopyMBB) != L) {
1111 if (SMBB != L->getLoopLatch())
1113 // If vr's live interval is extended from before the loop latch, do not
1115 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1116 PE = SMBB->pred_end(); PI != PE; ++PI) {
1117 MachineBasicBlock *PredMBB = *PI;
1118 if (PredMBB == SMBB)
1120 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1121 li_->getMBBEndIdx(PredMBB).getNextIndex().getBaseIndex()))
1128 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1129 /// two virtual registers from different register classes.
1131 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1133 unsigned Threshold) {
1134 // Then make sure the intervals are *short*.
1135 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1136 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1137 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1138 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1139 if (SmallSize > Threshold || LargeSize > Threshold)
1140 if ((float)std::distance(mri_->use_begin(SmallReg),
1141 mri_->use_end()) / SmallSize <
1142 (float)std::distance(mri_->use_begin(LargeReg),
1143 mri_->use_end()) / LargeSize)
1148 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1149 /// register with a physical register, check if any of the virtual register
1150 /// operand is a sub-register use or def. If so, make sure it won't result
1151 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1152 /// vr1024 = extract_subreg vr1025, 1
1154 /// vr1024 = mov8rr AH
1155 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1156 /// AH does not have a super-reg whose sub-register 1 is AH.
1158 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1161 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1162 E = mri_->reg_end(); I != E; ++I) {
1163 MachineOperand &O = I.getOperand();
1164 MachineInstr *MI = &*I;
1165 if (MI == CopyMI || JoinedCopies.count(MI))
1167 unsigned SubIdx = O.getSubReg();
1168 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1170 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1171 SubIdx = MI->getOperand(2).getImm();
1172 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1175 unsigned SrcReg = MI->getOperand(1).getReg();
1176 const TargetRegisterClass *RC =
1177 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1178 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1179 : mri_->getRegClass(SrcReg);
1180 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1184 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1185 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
1186 SubIdx = MI->getOperand(3).getImm();
1187 if (VirtReg == MI->getOperand(0).getReg()) {
1188 if (!tri_->getSubReg(PhysReg, SubIdx))
1191 unsigned DstReg = MI->getOperand(0).getReg();
1192 const TargetRegisterClass *RC =
1193 TargetRegisterInfo::isPhysicalRegister(DstReg)
1194 ? tri_->getPhysicalRegisterRegClass(DstReg)
1195 : mri_->getRegClass(DstReg);
1196 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1205 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1206 /// an extract_subreg where dst is a physical register, e.g.
1207 /// cl = EXTRACT_SUBREG reg1024, 1
1209 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1210 unsigned SrcReg, unsigned SubIdx,
1211 unsigned &RealDstReg) {
1212 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1213 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1214 assert(RealDstReg && "Invalid extract_subreg instruction!");
1216 // For this type of EXTRACT_SUBREG, conservatively
1217 // check if the live interval of the source register interfere with the
1218 // actual super physical register we are trying to coalesce with.
1219 LiveInterval &RHS = li_->getInterval(SrcReg);
1220 if (li_->hasInterval(RealDstReg) &&
1221 RHS.overlaps(li_->getInterval(RealDstReg))) {
1223 errs() << "Interfere with register ";
1224 li_->getInterval(RealDstReg).print(errs(), tri_);
1226 return false; // Not coalescable
1228 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1229 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1231 errs() << "Interfere with sub-register ";
1232 li_->getInterval(*SR).print(errs(), tri_);
1234 return false; // Not coalescable
1239 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1240 /// an insert_subreg where src is a physical register, e.g.
1241 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1243 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1244 unsigned SrcReg, unsigned SubIdx,
1245 unsigned &RealSrcReg) {
1246 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1247 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1248 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1250 LiveInterval &RHS = li_->getInterval(DstReg);
1251 if (li_->hasInterval(RealSrcReg) &&
1252 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1254 errs() << "Interfere with register ";
1255 li_->getInterval(RealSrcReg).print(errs(), tri_);
1257 return false; // Not coalescable
1259 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1260 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1262 errs() << "Interfere with sub-register ";
1263 li_->getInterval(*SR).print(errs(), tri_);
1265 return false; // Not coalescable
1270 /// getRegAllocPreference - Return register allocation preference register.
1272 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1273 MachineRegisterInfo *MRI,
1274 const TargetRegisterInfo *TRI) {
1275 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1277 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1278 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1281 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1282 /// which are the src/dst of the copy instruction CopyMI. This returns true
1283 /// if the copy was successfully coalesced away. If it is not currently
1284 /// possible to coalesce this interval, but it may be possible if other
1285 /// things get coalesced, then it returns true by reference in 'Again'.
1286 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1287 MachineInstr *CopyMI = TheCopy.MI;
1290 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1291 return false; // Already done.
1293 DEBUG(errs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1295 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1296 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1297 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1298 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
1299 unsigned SubIdx = 0;
1301 DstReg = CopyMI->getOperand(0).getReg();
1302 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1303 SrcReg = CopyMI->getOperand(1).getReg();
1304 SrcSubIdx = CopyMI->getOperand(2).getImm();
1305 } else if (isInsSubReg || isSubRegToReg) {
1306 DstReg = CopyMI->getOperand(0).getReg();
1307 DstSubIdx = CopyMI->getOperand(3).getImm();
1308 SrcReg = CopyMI->getOperand(2).getReg();
1309 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1310 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1311 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1312 // coalesced to a larger register so the subreg indices cancel out.
1313 DEBUG(errs() << "\tSource of insert_subreg or subreg_to_reg is already "
1314 "coalesced to another register.\n");
1315 return false; // Not coalescable.
1317 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1318 llvm_unreachable("Unrecognized copy instruction!");
1321 // If they are already joined we continue.
1322 if (SrcReg == DstReg) {
1323 DEBUG(errs() << "\tCopy already coalesced.\n");
1324 return false; // Not coalescable.
1327 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1328 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1330 // If they are both physical registers, we cannot join them.
1331 if (SrcIsPhys && DstIsPhys) {
1332 DEBUG(errs() << "\tCan not coalesce physregs.\n");
1333 return false; // Not coalescable.
1336 // We only join virtual registers with allocatable physical registers.
1337 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1338 DEBUG(errs() << "\tSrc reg is unallocatable physreg.\n");
1339 return false; // Not coalescable.
1341 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1342 DEBUG(errs() << "\tDst reg is unallocatable physreg.\n");
1343 return false; // Not coalescable.
1346 // Check that a physical source register is compatible with dst regclass
1348 unsigned SrcSubReg = SrcSubIdx ?
1349 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1350 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1351 const TargetRegisterClass *DstSubRC = DstRC;
1353 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1354 assert(DstSubRC && "Illegal subregister index");
1355 if (!DstSubRC->contains(SrcSubReg)) {
1356 DEBUG(errs() << "\tIncompatible destination regclass: "
1357 << tri_->getName(SrcSubReg) << " not in "
1358 << DstSubRC->getName() << ".\n");
1359 return false; // Not coalescable.
1363 // Check that a physical dst register is compatible with source regclass
1365 unsigned DstSubReg = DstSubIdx ?
1366 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1367 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1368 const TargetRegisterClass *SrcSubRC = SrcRC;
1370 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1371 assert(SrcSubRC && "Illegal subregister index");
1372 if (!SrcSubRC->contains(DstSubReg)) {
1373 DEBUG(errs() << "\tIncompatible source regclass: "
1374 << tri_->getName(DstSubReg) << " not in "
1375 << SrcSubRC->getName() << ".\n");
1377 return false; // Not coalescable.
1381 // Should be non-null only when coalescing to a sub-register class.
1382 bool CrossRC = false;
1383 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1384 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1385 const TargetRegisterClass *NewRC = NULL;
1386 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1387 unsigned RealDstReg = 0;
1388 unsigned RealSrcReg = 0;
1389 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1390 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1391 if (SrcIsPhys && isExtSubReg) {
1392 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1393 // coalesced with AX.
1394 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1396 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1397 // coalesced to a larger register so the subreg indices cancel out.
1398 if (DstSubIdx != SubIdx) {
1399 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1400 return false; // Not coalescable.
1403 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1405 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1406 // EAX = INSERT_SUBREG EAX, r1024, 0
1407 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1409 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1410 // coalesced to a larger register so the subreg indices cancel out.
1411 if (SrcSubIdx != SubIdx) {
1412 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1413 return false; // Not coalescable.
1416 DstReg = tri_->getSubReg(DstReg, SubIdx);
1418 } else if ((DstIsPhys && isExtSubReg) ||
1419 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1420 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1421 DEBUG(errs() << "\tSrc of extract_subreg already coalesced with reg"
1422 << " of a super-class.\n");
1423 return false; // Not coalescable.
1427 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1428 return false; // Not coalescable
1430 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1431 return false; // Not coalescable
1435 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1436 : CopyMI->getOperand(2).getSubReg();
1438 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1439 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1440 // coalesced to a larger register so the subreg indices cancel out.
1441 // Also check if the other larger register is of the same register
1442 // class as the would be resulting register.
1445 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1446 return false; // Not coalescable.
1450 if (!DstIsPhys && !SrcIsPhys) {
1451 if (isInsSubReg || isSubRegToReg) {
1452 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1453 } else // extract_subreg {
1454 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1457 DEBUG(errs() << "\t Conflicting sub-register indices.\n");
1458 return false; // Not coalescable
1461 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1462 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1463 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1464 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1465 Again = true; // May be possible to coalesce later.
1470 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1471 if (DisableCrossClassJoin)
1475 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1476 // with another? If it's the resulting destination register, then
1477 // the subidx must be propagated to uses (but only those defined
1478 // by the EXTRACT_SUBREG). If it's being coalesced into another
1479 // register, it should be safe because register is assumed to have
1480 // the register class of the super-register.
1482 // Process moves where one of the registers have a sub-register index.
1483 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1484 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1485 SubIdx = DstMO->getSubReg();
1487 if (SrcMO->getSubReg())
1488 // FIXME: can we handle this?
1490 // This is not an insert_subreg but it looks like one.
1491 // e.g. %reg1024:4 = MOV32rr %EAX
1494 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1495 return false; // Not coalescable
1499 SubIdx = SrcMO->getSubReg();
1501 // This is not a extract_subreg but it looks like one.
1502 // e.g. %cl = MOV16rr %reg1024:1
1505 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1506 return false; // Not coalescable
1512 unsigned LargeReg = SrcReg;
1513 unsigned SmallReg = DstReg;
1515 // Now determine the register class of the joined register.
1517 if (SubIdx && DstRC && DstRC->isASubClass()) {
1518 // This is a move to a sub-register class. However, the source is a
1519 // sub-register of a larger register class. We don't know what should
1520 // the register class be. FIXME.
1524 if (!DstIsPhys && !SrcIsPhys)
1526 } else if (!SrcIsPhys && !DstIsPhys) {
1527 NewRC = getCommonSubClass(SrcRC, DstRC);
1529 DEBUG(errs() << "\tDisjoint regclasses: "
1530 << SrcRC->getName() << ", "
1531 << DstRC->getName() << ".\n");
1532 return false; // Not coalescable.
1534 if (DstRC->getSize() > SrcRC->getSize())
1535 std::swap(LargeReg, SmallReg);
1538 // If we are joining two virtual registers and the resulting register
1539 // class is more restrictive (fewer register, smaller size). Check if it's
1540 // worth doing the merge.
1541 if (!SrcIsPhys && !DstIsPhys &&
1542 (isExtSubReg || DstRC->isASubClass()) &&
1543 !isWinToJoinCrossClass(LargeReg, SmallReg,
1544 allocatableRCRegs_[NewRC].count())) {
1545 DEBUG(errs() << "\tSrc/Dest are different register classes.\n");
1546 // Allow the coalescer to try again in case either side gets coalesced to
1547 // a physical register that's compatible with the other side. e.g.
1548 // r1024 = MOV32to32_ r1025
1549 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1550 Again = true; // May be possible to coalesce later.
1555 // Will it create illegal extract_subreg / insert_subreg?
1556 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1558 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1561 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1562 LiveInterval &DstInt = li_->getInterval(DstReg);
1563 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1564 "Register mapping is horribly broken!");
1567 errs() << "\t\tInspecting "; SrcInt.print(errs(), tri_);
1568 errs() << " and "; DstInt.print(errs(), tri_);
1572 // Save a copy of the virtual register live interval. We'll manually
1573 // merge this into the "real" physical register live interval this is
1575 LiveInterval *SavedLI = 0;
1577 SavedLI = li_->dupInterval(&SrcInt);
1578 else if (RealSrcReg)
1579 SavedLI = li_->dupInterval(&DstInt);
1581 // Check if it is necessary to propagate "isDead" property.
1582 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1583 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1584 bool isDead = mopd->isDead();
1586 // We need to be careful about coalescing a source physical register with a
1587 // virtual register. Once the coalescing is done, it cannot be broken and
1588 // these are not spillable! If the destination interval uses are far away,
1589 // think twice about coalescing them!
1590 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1591 // If the copy is in a loop, take care not to coalesce aggressively if the
1592 // src is coming in from outside the loop (or the dst is out of the loop).
1593 // If it's not in a loop, then determine whether to join them base purely
1594 // by the length of the interval.
1595 if (PhysJoinTweak) {
1597 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1598 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1600 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1601 Again = true; // May be possible to coalesce later.
1605 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1606 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1608 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1609 Again = true; // May be possible to coalesce later.
1614 // If the virtual register live interval is long but it has low use desity,
1615 // do not join them, instead mark the physical register as its allocation
1617 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1618 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1619 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1620 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1621 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1622 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1623 float Ratio = 1.0 / Threshold;
1624 if (Length > Threshold &&
1625 (((float)std::distance(mri_->use_begin(JoinVReg),
1626 mri_->use_end()) / Length) < Ratio)) {
1627 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1629 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1630 Again = true; // May be possible to coalesce later.
1637 // Okay, attempt to join these two intervals. On failure, this returns false.
1638 // Otherwise, if one of the intervals being joined is a physreg, this method
1639 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1640 // been modified, so we can use this information below to update aliases.
1641 bool Swapped = false;
1642 // If SrcInt is implicitly defined, it's safe to coalesce.
1643 bool isEmpty = SrcInt.empty();
1644 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1645 // Only coalesce an empty interval (defined by implicit_def) with
1646 // another interval which has a valno defined by the CopyMI and the CopyMI
1647 // is a kill of the implicit def.
1648 DEBUG(errs() << "Not profitable!\n");
1652 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1653 // Coalescing failed.
1655 // If definition of source is defined by trivial computation, try
1656 // rematerializing it.
1657 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1658 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1661 // If we can eliminate the copy without merging the live ranges, do so now.
1662 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1663 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1664 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1665 JoinedCopies.insert(CopyMI);
1669 // Otherwise, we are unable to join the intervals.
1670 DEBUG(errs() << "Interference!\n");
1671 Again = true; // May be possible to coalesce later.
1675 LiveInterval *ResSrcInt = &SrcInt;
1676 LiveInterval *ResDstInt = &DstInt;
1678 std::swap(SrcReg, DstReg);
1679 std::swap(ResSrcInt, ResDstInt);
1681 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1682 "LiveInterval::join didn't work right!");
1684 // If we're about to merge live ranges into a physical register live interval,
1685 // we have to update any aliased register's live ranges to indicate that they
1686 // have clobbered values for this range.
1687 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1688 // If this is a extract_subreg where dst is a physical register, e.g.
1689 // cl = EXTRACT_SUBREG reg1024, 1
1690 // then create and update the actual physical register allocated to RHS.
1691 if (RealDstReg || RealSrcReg) {
1692 LiveInterval &RealInt =
1693 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1694 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1695 E = SavedLI->vni_end(); I != E; ++I) {
1696 const VNInfo *ValNo = *I;
1697 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1698 false, // updated at *
1699 li_->getVNInfoAllocator());
1700 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1701 RealInt.addKills(NewValNo, ValNo->kills);
1702 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1704 RealInt.weight += SavedLI->weight;
1705 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1708 // Update the liveintervals of sub-registers.
1709 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1710 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, *ResSrcInt,
1711 li_->getVNInfoAllocator());
1714 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1715 // larger super-register.
1716 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1717 !SrcIsPhys && !DstIsPhys) {
1718 if ((isExtSubReg && !Swapped) ||
1719 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1720 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1721 std::swap(SrcReg, DstReg);
1722 std::swap(ResSrcInt, ResDstInt);
1726 // Coalescing to a virtual register that is of a sub-register class of the
1727 // other. Make sure the resulting register is set to the right register class.
1731 // This may happen even if it's cross-rc coalescing. e.g.
1732 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1733 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1734 // be allocate a register from GR64_ABCD.
1736 mri_->setRegClass(DstReg, NewRC);
1738 // Remember to delete the copy instruction.
1739 JoinedCopies.insert(CopyMI);
1741 // Some live range has been lengthened due to colaescing, eliminate the
1742 // unnecessary kills.
1743 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1744 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1745 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1747 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1749 // SrcReg is guarateed to be the register whose live interval that is
1751 li_->removeInterval(SrcReg);
1753 // Update regalloc hint.
1754 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1756 // Manually deleted the live interval copy.
1762 // If resulting interval has a preference that no longer fits because of subreg
1763 // coalescing, just clear the preference.
1764 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1765 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1766 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1767 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1768 if (!RC->contains(Preference))
1769 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1773 errs() << "\n\t\tJoined. Result = ";
1774 ResDstInt->print(errs(), tri_);
1782 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1783 /// compute what the resultant value numbers for each value in the input two
1784 /// ranges will be. This is complicated by copies between the two which can
1785 /// and will commonly cause multiple value numbers to be merged into one.
1787 /// VN is the value number that we're trying to resolve. InstDefiningValue
1788 /// keeps track of the new InstDefiningValue assignment for the result
1789 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1790 /// whether a value in this or other is a copy from the opposite set.
1791 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1792 /// already been assigned.
1794 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1795 /// contains the value number the copy is from.
1797 static unsigned ComputeUltimateVN(VNInfo *VNI,
1798 SmallVector<VNInfo*, 16> &NewVNInfo,
1799 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1800 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1801 SmallVector<int, 16> &ThisValNoAssignments,
1802 SmallVector<int, 16> &OtherValNoAssignments) {
1803 unsigned VN = VNI->id;
1805 // If the VN has already been computed, just return it.
1806 if (ThisValNoAssignments[VN] >= 0)
1807 return ThisValNoAssignments[VN];
1808 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1810 // If this val is not a copy from the other val, then it must be a new value
1811 // number in the destination.
1812 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1813 if (I == ThisFromOther.end()) {
1814 NewVNInfo.push_back(VNI);
1815 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1817 VNInfo *OtherValNo = I->second;
1819 // Otherwise, this *is* a copy from the RHS. If the other side has already
1820 // been computed, return it.
1821 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1822 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1824 // Mark this value number as currently being computed, then ask what the
1825 // ultimate value # of the other value is.
1826 ThisValNoAssignments[VN] = -2;
1827 unsigned UltimateVN =
1828 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1829 OtherValNoAssignments, ThisValNoAssignments);
1830 return ThisValNoAssignments[VN] = UltimateVN;
1833 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1834 return std::find(V.begin(), V.end(), Val) != V.end();
1837 static bool isValNoDefMove(const MachineInstr *MI, unsigned DR, unsigned SR,
1838 const TargetInstrInfo *TII,
1839 const TargetRegisterInfo *TRI) {
1840 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1841 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1843 else if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1844 DstReg = MI->getOperand(0).getReg();
1845 SrcReg = MI->getOperand(1).getReg();
1846 } else if (MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
1847 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1848 DstReg = MI->getOperand(0).getReg();
1849 SrcReg = MI->getOperand(2).getReg();
1852 return (SrcReg == SR || TRI->isSuperRegister(SR, SrcReg)) &&
1853 (DstReg == DR || TRI->isSuperRegister(DR, DstReg));
1856 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1857 /// the specified live interval is defined by a copy from the specified
1859 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1862 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1865 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1866 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1867 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1868 *tri_->getSuperRegisters(li.reg)) {
1869 // It's a sub-register live interval, we may not have precise information.
1871 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1872 if (DefMI && isValNoDefMove(DefMI, li.reg, Reg, tii_, tri_)) {
1873 // Cache computed info.
1874 LR->valno->def = LR->start;
1875 LR->valno->setCopy(DefMI);
1883 /// ValueLiveAt - Return true if the LiveRange pointed to by the given
1884 /// iterator, or any subsequent range with the same value number,
1885 /// is live at the given point.
1886 bool SimpleRegisterCoalescing::ValueLiveAt(LiveInterval::iterator LRItr,
1887 LiveInterval::iterator LREnd,
1888 SlotIndex defPoint) const {
1889 for (const VNInfo *valno = LRItr->valno;
1890 (LRItr != LREnd) && (LRItr->valno == valno); ++LRItr) {
1891 if (LRItr->contains(defPoint))
1899 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1900 /// caller of this method must guarantee that the RHS only contains a single
1901 /// value number and that the RHS is not defined by a copy from this
1902 /// interval. This returns false if the intervals are not joinable, or it
1903 /// joins them and returns true.
1904 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1905 assert(RHS.containsOneValue());
1907 // Some number (potentially more than one) value numbers in the current
1908 // interval may be defined as copies from the RHS. Scan the overlapping
1909 // portions of the LHS and RHS, keeping track of this and looking for
1910 // overlapping live ranges that are NOT defined as copies. If these exist, we
1913 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1914 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1916 if (LHSIt->start < RHSIt->start) {
1917 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1918 if (LHSIt != LHS.begin()) --LHSIt;
1919 } else if (RHSIt->start < LHSIt->start) {
1920 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1921 if (RHSIt != RHS.begin()) --RHSIt;
1924 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1927 // Determine if these live intervals overlap.
1928 bool Overlaps = false;
1929 if (LHSIt->start <= RHSIt->start)
1930 Overlaps = LHSIt->end > RHSIt->start;
1932 Overlaps = RHSIt->end > LHSIt->start;
1934 // If the live intervals overlap, there are two interesting cases: if the
1935 // LHS interval is defined by a copy from the RHS, it's ok and we record
1936 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1937 // coalesce these live ranges and we bail out.
1939 // If we haven't already recorded that this value # is safe, check it.
1940 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1941 // Copy from the RHS?
1942 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1943 return false; // Nope, bail out.
1945 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
1946 // Here is an interesting situation:
1948 // vr1025 = copy vr1024
1953 // Even though vr1025 is copied from vr1024, it's not safe to
1954 // coalesce them since the live range of vr1025 intersects the
1955 // def of vr1024. This happens because vr1025 is assigned the
1956 // value of the previous iteration of vr1024.
1958 EliminatedLHSVals.push_back(LHSIt->valno);
1961 // We know this entire LHS live range is okay, so skip it now.
1962 if (++LHSIt == LHSEnd) break;
1966 if (LHSIt->end < RHSIt->end) {
1967 if (++LHSIt == LHSEnd) break;
1969 // One interesting case to check here. It's possible that we have
1970 // something like "X3 = Y" which defines a new value number in the LHS,
1971 // and is the last use of this liverange of the RHS. In this case, we
1972 // want to notice this copy (so that it gets coalesced away) even though
1973 // the live ranges don't actually overlap.
1974 if (LHSIt->start == RHSIt->end) {
1975 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1976 // We already know that this value number is going to be merged in
1977 // if coalescing succeeds. Just skip the liverange.
1978 if (++LHSIt == LHSEnd) break;
1980 // Otherwise, if this is a copy from the RHS, mark it as being merged
1982 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1983 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
1984 // Here is an interesting situation:
1986 // vr1025 = copy vr1024
1991 // Even though vr1025 is copied from vr1024, it's not safe to
1992 // coalesced them since live range of vr1025 intersects the
1993 // def of vr1024. This happens because vr1025 is assigned the
1994 // value of the previous iteration of vr1024.
1996 EliminatedLHSVals.push_back(LHSIt->valno);
1998 // We know this entire LHS live range is okay, so skip it now.
1999 if (++LHSIt == LHSEnd) break;
2004 if (++RHSIt == RHSEnd) break;
2008 // If we got here, we know that the coalescing will be successful and that
2009 // the value numbers in EliminatedLHSVals will all be merged together. Since
2010 // the most common case is that EliminatedLHSVals has a single number, we
2011 // optimize for it: if there is more than one value, we merge them all into
2012 // the lowest numbered one, then handle the interval as if we were merging
2013 // with one value number.
2014 VNInfo *LHSValNo = NULL;
2015 if (EliminatedLHSVals.size() > 1) {
2016 // Loop through all the equal value numbers merging them into the smallest
2018 VNInfo *Smallest = EliminatedLHSVals[0];
2019 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
2020 if (EliminatedLHSVals[i]->id < Smallest->id) {
2021 // Merge the current notion of the smallest into the smaller one.
2022 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2023 Smallest = EliminatedLHSVals[i];
2025 // Merge into the smallest.
2026 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2029 LHSValNo = Smallest;
2030 } else if (EliminatedLHSVals.empty()) {
2031 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2032 *tri_->getSuperRegisters(LHS.reg))
2033 // Imprecise sub-register information. Can't handle it.
2035 llvm_unreachable("No copies from the RHS?");
2037 LHSValNo = EliminatedLHSVals[0];
2040 // Okay, now that there is a single LHS value number that we're merging the
2041 // RHS into, update the value number info for the LHS to indicate that the
2042 // value number is defined where the RHS value number was.
2043 const VNInfo *VNI = RHS.getValNumInfo(0);
2044 LHSValNo->def = VNI->def;
2045 LHSValNo->setCopy(VNI->getCopy());
2047 // Okay, the final step is to loop over the RHS live intervals, adding them to
2049 if (VNI->hasPHIKill())
2050 LHSValNo->setHasPHIKill(true);
2051 LHS.addKills(LHSValNo, VNI->kills);
2052 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2054 LHS.ComputeJoinedWeight(RHS);
2056 // Update regalloc hint if both are virtual registers.
2057 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2058 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2059 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2060 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2061 if (RHSPref != LHSPref)
2062 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2065 // Update the liveintervals of sub-registers.
2066 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2067 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2068 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, LHS,
2069 li_->getVNInfoAllocator());
2074 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2075 /// returns false. Otherwise, if one of the intervals being joined is a
2076 /// physreg, this method always canonicalizes LHS to be it. The output
2077 /// "RHS" will not have been modified, so we can use this information
2078 /// below to update aliases.
2080 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2082 // Compute the final value assignment, assuming that the live ranges can be
2084 SmallVector<int, 16> LHSValNoAssignments;
2085 SmallVector<int, 16> RHSValNoAssignments;
2086 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2087 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2088 SmallVector<VNInfo*, 16> NewVNInfo;
2090 // If a live interval is a physical register, conservatively check if any
2091 // of its sub-registers is overlapping the live interval of the virtual
2092 // register. If so, do not coalesce.
2093 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2094 *tri_->getSubRegisters(LHS.reg)) {
2095 // If it's coalescing a virtual register to a physical register, estimate
2096 // its live interval length. This is the *cost* of scanning an entire live
2097 // interval. If the cost is low, we'll do an exhaustive check instead.
2099 // If this is something like this:
2107 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2108 // less conservative check. It's possible a sub-register is defined before
2109 // v1024 (or live in) and live out of BB1.
2110 if (RHS.containsOneValue() &&
2111 li_->intervalIsInOneMBB(RHS) &&
2112 li_->getApproximateInstructionCount(RHS) <= 10) {
2113 // Perform a more exhaustive check for some common cases.
2114 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2117 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2118 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2120 errs() << "Interfere with sub-register ";
2121 li_->getInterval(*SR).print(errs(), tri_);
2126 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2127 *tri_->getSubRegisters(RHS.reg)) {
2128 if (LHS.containsOneValue() &&
2129 li_->getApproximateInstructionCount(LHS) <= 10) {
2130 // Perform a more exhaustive check for some common cases.
2131 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2134 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2135 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2137 errs() << "Interfere with sub-register ";
2138 li_->getInterval(*SR).print(errs(), tri_);
2145 // Compute ultimate value numbers for the LHS and RHS values.
2146 if (RHS.containsOneValue()) {
2147 // Copies from a liveinterval with a single value are simple to handle and
2148 // very common, handle the special case here. This is important, because
2149 // often RHS is small and LHS is large (e.g. a physreg).
2151 // Find out if the RHS is defined as a copy from some value in the LHS.
2152 int RHSVal0DefinedFromLHS = -1;
2154 VNInfo *RHSValNoInfo = NULL;
2155 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2156 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2157 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2158 // If RHS is not defined as a copy from the LHS, we can use simpler and
2159 // faster checks to see if the live ranges are coalescable. This joiner
2160 // can't swap the LHS/RHS intervals though.
2161 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2162 return SimpleJoin(LHS, RHS);
2164 RHSValNoInfo = RHSValNoInfo0;
2167 // It was defined as a copy from the LHS, find out what value # it is.
2169 LHS.getLiveRangeContaining(RHSValNoInfo0->def.getPrevSlot())->valno;
2170 RHSValID = RHSValNoInfo->id;
2171 RHSVal0DefinedFromLHS = RHSValID;
2174 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2175 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2176 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2178 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2179 // should now get updated.
2180 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2183 unsigned VN = VNI->id;
2184 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2185 if (LHSSrcReg != RHS.reg) {
2186 // If this is not a copy from the RHS, its value number will be
2187 // unmodified by the coalescing.
2188 NewVNInfo[VN] = VNI;
2189 LHSValNoAssignments[VN] = VN;
2190 } else if (RHSValID == -1) {
2191 // Otherwise, it is a copy from the RHS, and we don't already have a
2192 // value# for it. Keep the current value number, but remember it.
2193 LHSValNoAssignments[VN] = RHSValID = VN;
2194 NewVNInfo[VN] = RHSValNoInfo;
2195 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2197 // Otherwise, use the specified value #.
2198 LHSValNoAssignments[VN] = RHSValID;
2199 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2200 NewVNInfo[VN] = RHSValNoInfo;
2201 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2205 NewVNInfo[VN] = VNI;
2206 LHSValNoAssignments[VN] = VN;
2210 assert(RHSValID != -1 && "Didn't find value #?");
2211 RHSValNoAssignments[0] = RHSValID;
2212 if (RHSVal0DefinedFromLHS != -1) {
2213 // This path doesn't go through ComputeUltimateVN so just set
2215 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2218 // Loop over the value numbers of the LHS, seeing if any are defined from
2220 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2223 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2226 // DstReg is known to be a register in the LHS interval. If the src is
2227 // from the RHS interval, we can use its value #.
2228 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2231 // Figure out the value # from the RHS.
2232 LHSValsDefinedFromRHS[VNI]=
2233 RHS.getLiveRangeContaining(VNI->def.getPrevSlot())->valno;
2236 // Loop over the value numbers of the RHS, seeing if any are defined from
2238 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2241 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2244 // DstReg is known to be a register in the RHS interval. If the src is
2245 // from the LHS interval, we can use its value #.
2246 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2249 // Figure out the value # from the LHS.
2250 RHSValsDefinedFromLHS[VNI]=
2251 LHS.getLiveRangeContaining(VNI->def.getPrevSlot())->valno;
2254 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2255 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2256 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2258 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2261 unsigned VN = VNI->id;
2262 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2264 ComputeUltimateVN(VNI, NewVNInfo,
2265 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2266 LHSValNoAssignments, RHSValNoAssignments);
2268 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2271 unsigned VN = VNI->id;
2272 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2274 // If this value number isn't a copy from the LHS, it's a new number.
2275 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2276 NewVNInfo.push_back(VNI);
2277 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2281 ComputeUltimateVN(VNI, NewVNInfo,
2282 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2283 RHSValNoAssignments, LHSValNoAssignments);
2287 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2288 // interval lists to see if these intervals are coalescable.
2289 LiveInterval::const_iterator I = LHS.begin();
2290 LiveInterval::const_iterator IE = LHS.end();
2291 LiveInterval::const_iterator J = RHS.begin();
2292 LiveInterval::const_iterator JE = RHS.end();
2294 // Skip ahead until the first place of potential sharing.
2295 if (I->start < J->start) {
2296 I = std::upper_bound(I, IE, J->start);
2297 if (I != LHS.begin()) --I;
2298 } else if (J->start < I->start) {
2299 J = std::upper_bound(J, JE, I->start);
2300 if (J != RHS.begin()) --J;
2304 // Determine if these two live ranges overlap.
2306 if (I->start < J->start) {
2307 Overlaps = I->end > J->start;
2309 Overlaps = J->end > I->start;
2312 // If so, check value # info to determine if they are really different.
2314 // If the live range overlap will map to the same value number in the
2315 // result liverange, we can still coalesce them. If not, we can't.
2316 if (LHSValNoAssignments[I->valno->id] !=
2317 RHSValNoAssignments[J->valno->id])
2321 if (I->end < J->end) {
2330 // Update kill info. Some live ranges are extended due to copy coalescing.
2331 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2332 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2333 VNInfo *VNI = I->first;
2334 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2335 NewVNInfo[LHSValID]->removeKill(VNI->def);
2336 if (VNI->hasPHIKill())
2337 NewVNInfo[LHSValID]->setHasPHIKill(true);
2338 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2341 // Update kill info. Some live ranges are extended due to copy coalescing.
2342 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2343 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2344 VNInfo *VNI = I->first;
2345 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2346 NewVNInfo[RHSValID]->removeKill(VNI->def);
2347 if (VNI->hasPHIKill())
2348 NewVNInfo[RHSValID]->setHasPHIKill(true);
2349 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2352 // If we get here, we know that we can coalesce the live ranges. Ask the
2353 // intervals to coalesce themselves now.
2354 if ((RHS.ranges.size() > LHS.ranges.size() &&
2355 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2356 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2357 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2361 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2369 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2370 // depth of the basic block (the unsigned), and then on the MBB number.
2371 struct DepthMBBCompare {
2372 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2373 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2374 if (LHS.first > RHS.first) return true; // Deeper loops first
2375 return LHS.first == RHS.first &&
2376 LHS.second->getNumber() < RHS.second->getNumber();
2381 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2382 std::vector<CopyRec> &TryAgain) {
2383 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
2385 std::vector<CopyRec> VirtCopies;
2386 std::vector<CopyRec> PhysCopies;
2387 std::vector<CopyRec> ImpDefCopies;
2388 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2390 MachineInstr *Inst = MII++;
2392 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2393 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2394 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2395 DstReg = Inst->getOperand(0).getReg();
2396 SrcReg = Inst->getOperand(1).getReg();
2397 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2398 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
2399 DstReg = Inst->getOperand(0).getReg();
2400 SrcReg = Inst->getOperand(2).getReg();
2401 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2404 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2405 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2406 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2407 ImpDefCopies.push_back(CopyRec(Inst, 0));
2408 else if (SrcIsPhys || DstIsPhys)
2409 PhysCopies.push_back(CopyRec(Inst, 0));
2411 VirtCopies.push_back(CopyRec(Inst, 0));
2414 // Try coalescing implicit copies first, followed by copies to / from
2415 // physical registers, then finally copies from virtual registers to
2416 // virtual registers.
2417 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2418 CopyRec &TheCopy = ImpDefCopies[i];
2420 if (!JoinCopy(TheCopy, Again))
2422 TryAgain.push_back(TheCopy);
2424 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2425 CopyRec &TheCopy = PhysCopies[i];
2427 if (!JoinCopy(TheCopy, Again))
2429 TryAgain.push_back(TheCopy);
2431 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2432 CopyRec &TheCopy = VirtCopies[i];
2434 if (!JoinCopy(TheCopy, Again))
2436 TryAgain.push_back(TheCopy);
2440 void SimpleRegisterCoalescing::joinIntervals() {
2441 DEBUG(errs() << "********** JOINING INTERVALS ***********\n");
2443 std::vector<CopyRec> TryAgainList;
2444 if (loopInfo->empty()) {
2445 // If there are no loops in the function, join intervals in function order.
2446 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2448 CopyCoalesceInMBB(I, TryAgainList);
2450 // Otherwise, join intervals in inner loops before other intervals.
2451 // Unfortunately we can't just iterate over loop hierarchy here because
2452 // there may be more MBB's than BB's. Collect MBB's for sorting.
2454 // Join intervals in the function prolog first. We want to join physical
2455 // registers with virtual registers before the intervals got too long.
2456 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2457 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2458 MachineBasicBlock *MBB = I;
2459 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2462 // Sort by loop depth.
2463 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2465 // Finally, join intervals in loop nest order.
2466 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2467 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2470 // Joining intervals can allow other intervals to be joined. Iteratively join
2471 // until we make no progress.
2472 bool ProgressMade = true;
2473 while (ProgressMade) {
2474 ProgressMade = false;
2476 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2477 CopyRec &TheCopy = TryAgainList[i];
2482 bool Success = JoinCopy(TheCopy, Again);
2483 if (Success || !Again) {
2484 TheCopy.MI = 0; // Mark this one as done.
2485 ProgressMade = true;
2491 /// Return true if the two specified registers belong to different register
2492 /// classes. The registers may be either phys or virt regs.
2494 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2495 unsigned RegB) const {
2496 // Get the register classes for the first reg.
2497 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2498 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2499 "Shouldn't consider two physregs!");
2500 return !mri_->getRegClass(RegB)->contains(RegA);
2503 // Compare against the regclass for the second reg.
2504 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2505 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2506 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2507 return RegClassA != RegClassB;
2509 return !RegClassA->contains(RegB);
2512 /// lastRegisterUse - Returns the last use of the specific register between
2513 /// cycles Start and End or NULL if there are no uses.
2515 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
2518 SlotIndex &UseIdx) const{
2519 UseIdx = SlotIndex();
2520 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2521 MachineOperand *LastUse = NULL;
2522 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2523 E = mri_->use_end(); I != E; ++I) {
2524 MachineOperand &Use = I.getOperand();
2525 MachineInstr *UseMI = Use.getParent();
2526 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2527 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2529 // Ignore identity copies.
2531 SlotIndex Idx = li_->getInstructionIndex(UseMI);
2532 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
2533 // that compares higher than any other interval.
2534 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2536 UseIdx = Idx.getUseIndex();
2542 SlotIndex s = Start;
2543 SlotIndex e = End.getPrevSlot().getBaseIndex();
2545 // Skip deleted instructions
2546 MachineInstr *MI = li_->getInstructionFromIndex(e);
2547 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
2548 e = e.getPrevIndex();
2549 MI = li_->getInstructionFromIndex(e);
2551 if (e < s || MI == NULL)
2554 // Ignore identity copies.
2555 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2556 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2558 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2559 MachineOperand &Use = MI->getOperand(i);
2560 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2561 tri_->regsOverlap(Use.getReg(), Reg)) {
2562 UseIdx = e.getUseIndex();
2567 e = e.getPrevIndex();
2574 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2575 if (TargetRegisterInfo::isPhysicalRegister(reg))
2576 errs() << tri_->getName(reg);
2578 errs() << "%reg" << reg;
2581 void SimpleRegisterCoalescing::releaseMemory() {
2582 JoinedCopies.clear();
2583 ReMatCopies.clear();
2587 /// Returns true if the given live interval is zero length.
2588 static bool isZeroLengthInterval(LiveInterval *li, LiveIntervals *li_) {
2589 for (LiveInterval::Ranges::const_iterator
2590 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2591 if (i->end.getPrevIndex() > i->start)
2597 void SimpleRegisterCoalescing::CalculateSpillWeights() {
2598 SmallSet<unsigned, 4> Processed;
2599 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2600 mbbi != mbbe; ++mbbi) {
2601 MachineBasicBlock* MBB = mbbi;
2602 SlotIndex MBBEnd = li_->getMBBEndIdx(MBB);
2603 MachineLoop* loop = loopInfo->getLoopFor(MBB);
2604 unsigned loopDepth = loop ? loop->getLoopDepth() : 0;
2605 bool isExiting = loop ? loop->isLoopExiting(MBB) : false;
2607 for (MachineBasicBlock::const_iterator mii = MBB->begin(), mie = MBB->end();
2608 mii != mie; ++mii) {
2609 const MachineInstr *MI = mii;
2610 if (tii_->isIdentityCopy(*MI))
2613 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
2616 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2617 const MachineOperand &mopi = MI->getOperand(i);
2618 if (!mopi.isReg() || mopi.getReg() == 0)
2620 unsigned Reg = mopi.getReg();
2621 if (!TargetRegisterInfo::isVirtualRegister(mopi.getReg()))
2623 // Multiple uses of reg by the same instruction. It should not
2624 // contribute to spill weight again.
2625 if (!Processed.insert(Reg))
2628 bool HasDef = mopi.isDef();
2629 bool HasUse = !HasDef;
2630 for (unsigned j = i+1; j != e; ++j) {
2631 const MachineOperand &mopj = MI->getOperand(j);
2632 if (!mopj.isReg() || mopj.getReg() != Reg)
2634 HasDef |= mopj.isDef();
2635 HasUse |= mopj.isUse();
2636 if (HasDef && HasUse)
2640 LiveInterval &RegInt = li_->getInterval(Reg);
2641 float Weight = li_->getSpillWeight(HasDef, HasUse, loopDepth);
2642 if (HasDef && isExiting) {
2643 // Looks like this is a loop count variable update.
2644 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
2645 const LiveRange *DLR =
2646 li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
2647 if (DLR->end > MBBEnd)
2650 RegInt.weight += Weight;
2656 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2657 LiveInterval &LI = *I->second;
2658 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2659 // If the live interval length is essentially zero, i.e. in every live
2660 // range the use follows def immediately, it doesn't make sense to spill
2661 // it and hope it will be easier to allocate for this li.
2662 if (isZeroLengthInterval(&LI, li_)) {
2663 LI.weight = HUGE_VALF;
2667 bool isLoad = false;
2668 SmallVector<LiveInterval*, 4> SpillIs;
2669 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2670 // If all of the definitions of the interval are re-materializable,
2671 // it is a preferred candidate for spilling. If non of the defs are
2672 // loads, then it's potentially very cheap to re-materialize.
2673 // FIXME: this gets much more complicated once we support non-trivial
2674 // re-materialization.
2681 // Slightly prefer live interval that has been assigned a preferred reg.
2682 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2683 if (Hint.first || Hint.second)
2686 // Divide the weight of the interval by its size. This encourages
2687 // spilling of intervals that are large and have few uses, and
2688 // discourages spilling of small intervals with many uses.
2689 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2695 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2697 mri_ = &fn.getRegInfo();
2698 tm_ = &fn.getTarget();
2699 tri_ = tm_->getRegisterInfo();
2700 tii_ = tm_->getInstrInfo();
2701 li_ = &getAnalysis<LiveIntervals>();
2702 AA = &getAnalysis<AliasAnalysis>();
2703 loopInfo = &getAnalysis<MachineLoopInfo>();
2705 DEBUG(errs() << "********** SIMPLE REGISTER COALESCING **********\n"
2706 << "********** Function: "
2707 << ((Value*)mf_->getFunction())->getName() << '\n');
2709 allocatableRegs_ = tri_->getAllocatableSet(fn);
2710 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2711 E = tri_->regclass_end(); I != E; ++I)
2712 allocatableRCRegs_.insert(std::make_pair(*I,
2713 tri_->getAllocatableSet(fn, *I)));
2715 // Join (coalesce) intervals if requested.
2716 if (EnableJoining) {
2719 errs() << "********** INTERVALS POST JOINING **********\n";
2720 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2721 I->second->print(errs(), tri_);
2727 // Perform a final pass over the instructions and compute spill weights
2728 // and remove identity moves.
2729 SmallVector<unsigned, 4> DeadDefs;
2730 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2731 mbbi != mbbe; ++mbbi) {
2732 MachineBasicBlock* mbb = mbbi;
2733 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2735 MachineInstr *MI = mii;
2736 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2737 if (JoinedCopies.count(MI)) {
2738 // Delete all coalesced copies.
2739 bool DoDelete = true;
2740 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2741 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2742 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2743 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
2744 "Unrecognized copy instruction");
2745 DstReg = MI->getOperand(0).getReg();
2746 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2747 // Do not delete extract_subreg, insert_subreg of physical
2748 // registers unless the definition is dead. e.g.
2749 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2750 // or else the scavenger may complain. LowerSubregs will
2751 // delete them later.
2754 if (MI->registerDefIsDead(DstReg)) {
2755 LiveInterval &li = li_->getInterval(DstReg);
2756 if (!ShortenDeadCopySrcLiveRange(li, MI))
2757 ShortenDeadCopyLiveRange(li, MI);
2763 li_->RemoveMachineInstrFromMaps(MI);
2764 mii = mbbi->erase(mii);
2770 // Now check if this is a remat'ed def instruction which is now dead.
2771 if (ReMatDefs.count(MI)) {
2773 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2774 const MachineOperand &MO = MI->getOperand(i);
2777 unsigned Reg = MO.getReg();
2780 if (TargetRegisterInfo::isVirtualRegister(Reg))
2781 DeadDefs.push_back(Reg);
2784 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2785 !mri_->use_empty(Reg)) {
2791 while (!DeadDefs.empty()) {
2792 unsigned DeadDef = DeadDefs.back();
2793 DeadDefs.pop_back();
2794 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2796 li_->RemoveMachineInstrFromMaps(mii);
2797 mii = mbbi->erase(mii);
2803 // If the move will be an identity move delete it
2804 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2805 if (isMove && SrcReg == DstReg) {
2806 if (li_->hasInterval(SrcReg)) {
2807 LiveInterval &RegInt = li_->getInterval(SrcReg);
2808 // If def of this move instruction is dead, remove its live range
2809 // from the dstination register's live interval.
2810 if (MI->registerDefIsDead(DstReg)) {
2811 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2812 ShortenDeadCopyLiveRange(RegInt, MI);
2815 li_->RemoveMachineInstrFromMaps(MI);
2816 mii = mbbi->erase(mii);
2824 CalculateSpillWeights();
2830 /// print - Implement the dump method.
2831 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2835 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2836 return new SimpleRegisterCoalescing();
2839 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2840 DEFINING_FILE_FOR(SimpleRegisterCoalescing)