1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
40 STATISTIC(numJoins , "Number of interval joins performed");
41 STATISTIC(numCrossRCs , "Number of cross class joins performed");
42 STATISTIC(numCommutes , "Number of instruction commuting performed");
43 STATISTIC(numExtends , "Number of copies extended");
44 STATISTIC(NumReMats , "Number of instructions re-materialized");
45 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
46 STATISTIC(numAborts , "Number of times interval joining aborted");
47 STATISTIC(numDeadValNo, "Number of valno def marked dead");
49 char SimpleRegisterCoalescing::ID = 0;
51 EnableJoining("join-liveintervals",
52 cl::desc("Coalesce copies (default=true)"),
56 DisableCrossClassJoin("disable-cross-class-join",
57 cl::desc("Avoid coalescing cross register class copies"),
58 cl::init(false), cl::Hidden);
61 PhysJoinTweak("tweak-phys-join-heuristics",
62 cl::desc("Tweak heuristics for joining phys reg with vr"),
63 cl::init(false), cl::Hidden);
65 static RegisterPass<SimpleRegisterCoalescing>
66 X("simple-register-coalescing", "Simple Register Coalescing");
68 // Declare that we implement the RegisterCoalescer interface
69 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
71 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
73 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<LiveIntervals>();
76 AU.addPreserved<LiveIntervals>();
77 AU.addRequired<MachineLoopInfo>();
78 AU.addPreserved<MachineLoopInfo>();
79 AU.addPreservedID(MachineDominatorsID);
81 AU.addPreservedID(StrongPHIEliminationID);
83 AU.addPreservedID(PHIEliminationID);
84 AU.addPreservedID(TwoAddressInstructionPassID);
85 MachineFunctionPass::getAnalysisUsage(AU);
88 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
89 /// being the source and IntB being the dest, thus this defines a value number
90 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
91 /// see if we can merge these two pieces of B into a single value number,
92 /// eliminating a copy. For example:
96 /// B1 = A3 <- this copy
98 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
99 /// value number to be replaced with B0 (which simplifies the B liveinterval).
101 /// This returns true if an interval was modified.
103 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
105 MachineInstr *CopyMI) {
106 LiveIndex CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
108 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
109 // the example above.
110 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
111 assert(BLR != IntB.end() && "Live range not found!");
112 VNInfo *BValNo = BLR->valno;
114 // Get the location that B is defined at. Two options: either this value has
115 // an unknown definition point or it is defined at CopyIdx. If unknown, we
117 if (!BValNo->getCopy()) return false;
118 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
120 // AValNo is the value number in A that defines the copy, A3 in the example.
121 LiveIndex CopyUseIdx = li_->getUseIndex(CopyIdx);
122 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
123 assert(ALR != IntA.end() && "Live range not found!");
124 VNInfo *AValNo = ALR->valno;
125 // If it's re-defined by an early clobber somewhere in the live range, then
126 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
128 // 172 %ECX<def> = MOV32rr %reg1039<kill>
129 // 180 INLINEASM <es:subl $5,$1
130 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
131 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
132 // 188 %EAX<def> = MOV32rr %EAX<kill>
133 // 196 %ECX<def> = MOV32rr %ECX<kill>
134 // 204 %ECX<def> = MOV32rr %ECX<kill>
135 // 212 %EAX<def> = MOV32rr %EAX<kill>
136 // 220 %EAX<def> = MOV32rr %EAX
137 // 228 %reg1039<def> = MOV32rr %ECX<kill>
138 // The early clobber operand ties ECX input to the ECX def.
140 // The live interval of ECX is represented as this:
141 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
142 // The coalescer has no idea there was a def in the middle of [174,230].
143 if (AValNo->hasRedefByEC())
146 // If AValNo is defined as a copy from IntB, we can potentially process this.
147 // Get the instruction that defines this value number.
148 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
149 if (!SrcReg) return false; // Not defined by a copy.
151 // If the value number is not defined by a copy instruction, ignore it.
153 // If the source register comes from an interval other than IntB, we can't
155 if (SrcReg != IntB.reg) return false;
157 // Get the LiveRange in IntB that this value number starts with.
158 LiveInterval::iterator ValLR =
159 IntB.FindLiveRangeContaining(li_->getPrevSlot(AValNo->def));
160 assert(ValLR != IntB.end() && "Live range not found!");
162 // Make sure that the end of the live range is inside the same block as
164 MachineInstr *ValLREndInst =
165 li_->getInstructionFromIndex(li_->getPrevSlot(ValLR->end));
167 ValLREndInst->getParent() != CopyMI->getParent()) return false;
169 // Okay, we now know that ValLR ends in the same block that the CopyMI
170 // live-range starts. If there are no intervening live ranges between them in
171 // IntB, we can merge them.
172 if (ValLR+1 != BLR) return false;
174 // If a live interval is a physical register, conservatively check if any
175 // of its sub-registers is overlapping the live interval of the virtual
176 // register. If so, do not coalesce.
177 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
178 *tri_->getSubRegisters(IntB.reg)) {
179 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
180 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
182 errs() << "Interfere with sub-register ";
183 li_->getInterval(*SR).print(errs(), tri_);
190 errs() << "\nExtending: ";
191 IntB.print(errs(), tri_);
194 LiveIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
195 // We are about to delete CopyMI, so need to remove it as the 'instruction
196 // that defines this value #'. Update the the valnum with the new defining
198 BValNo->def = FillerStart;
201 // Okay, we can merge them. We need to insert a new liverange:
202 // [ValLR.end, BLR.begin) of either value number, then we merge the
203 // two value numbers.
204 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
206 // If the IntB live range is assigned to a physical register, and if that
207 // physreg has sub-registers, update their live intervals as well.
208 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
209 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
210 LiveInterval &SRLI = li_->getInterval(*SR);
211 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
212 SRLI.getNextValue(FillerStart, 0, true,
213 li_->getVNInfoAllocator())));
217 // Okay, merge "B1" into the same value number as "B0".
218 if (BValNo != ValLR->valno) {
219 IntB.addKills(ValLR->valno, BValNo->kills);
220 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
223 errs() << " result = ";
224 IntB.print(errs(), tri_);
228 // If the source instruction was killing the source register before the
229 // merge, unset the isKill marker given the live range has been extended.
230 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
232 ValLREndInst->getOperand(UIdx).setIsKill(false);
233 ValLR->valno->removeKill(FillerStart);
236 // If the copy instruction was killing the destination register before the
237 // merge, find the last use and trim the live range. That will also add the
239 if (CopyMI->killsRegister(IntA.reg))
240 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
246 /// HasOtherReachingDefs - Return true if there are definitions of IntB
247 /// other than BValNo val# that can reach uses of AValno val# of IntA.
248 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
252 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
254 if (AI->valno != AValNo) continue;
255 LiveInterval::Ranges::iterator BI =
256 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
257 if (BI != IntB.ranges.begin())
259 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
260 if (BI->valno == BValNo)
262 if (BI->start <= AI->start && BI->end > AI->start)
264 if (BI->start > AI->start && BI->start < AI->end)
272 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
273 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
275 MachineOperand &MO = MI->getOperand(i);
276 if (MO.isReg() && MO.isImplicit())
277 NewMI->addOperand(MO);
281 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
282 /// being the source and IntB being the dest, thus this defines a value number
283 /// in IntB. If the source value number (in IntA) is defined by a commutable
284 /// instruction and its other operand is coalesced to the copy dest register,
285 /// see if we can transform the copy into a noop by commuting the definition. For
288 /// A3 = op A2 B0<kill>
290 /// B1 = A3 <- this copy
292 /// = op A3 <- more uses
296 /// B2 = op B0 A2<kill>
298 /// B1 = B2 <- now an identify copy
300 /// = op B2 <- more uses
302 /// This returns true if an interval was modified.
304 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
306 MachineInstr *CopyMI) {
308 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
310 // FIXME: For now, only eliminate the copy by commuting its def when the
311 // source register is a virtual register. We want to guard against cases
312 // where the copy is a back edge copy and commuting the def lengthen the
313 // live interval of the source register to the entire loop.
314 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
317 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
318 // the example above.
319 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
320 assert(BLR != IntB.end() && "Live range not found!");
321 VNInfo *BValNo = BLR->valno;
323 // Get the location that B is defined at. Two options: either this value has
324 // an unknown definition point or it is defined at CopyIdx. If unknown, we
326 if (!BValNo->getCopy()) return false;
327 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
329 // AValNo is the value number in A that defines the copy, A3 in the example.
330 LiveInterval::iterator ALR =
331 IntA.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
333 assert(ALR != IntA.end() && "Live range not found!");
334 VNInfo *AValNo = ALR->valno;
335 // If other defs can reach uses of this def, then it's not safe to perform
336 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
338 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
339 AValNo->isUnused() || AValNo->hasPHIKill())
341 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
342 const TargetInstrDesc &TID = DefMI->getDesc();
343 if (!TID.isCommutable())
345 // If DefMI is a two-address instruction then commuting it will change the
346 // destination register.
347 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
348 assert(DefIdx != -1);
350 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
352 unsigned Op1, Op2, NewDstIdx;
353 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
357 else if (Op2 == UseOpIdx)
362 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
363 unsigned NewReg = NewDstMO.getReg();
364 if (NewReg != IntB.reg || !NewDstMO.isKill())
367 // Make sure there are no other definitions of IntB that would reach the
368 // uses which the new definition can reach.
369 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
372 // If some of the uses of IntA.reg is already coalesced away, return false.
373 // It's not possible to determine whether it's safe to perform the coalescing.
374 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
375 UE = mri_->use_end(); UI != UE; ++UI) {
376 MachineInstr *UseMI = &*UI;
377 LiveIndex UseIdx = li_->getInstructionIndex(UseMI);
378 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
379 if (ULR == IntA.end())
381 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
385 // At this point we have decided that it is legal to do this
386 // transformation. Start by commuting the instruction.
387 MachineBasicBlock *MBB = DefMI->getParent();
388 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
391 if (NewMI != DefMI) {
392 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
393 MBB->insert(DefMI, NewMI);
396 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
397 NewMI->getOperand(OpIdx).setIsKill();
399 bool BHasPHIKill = BValNo->hasPHIKill();
400 SmallVector<VNInfo*, 4> BDeadValNos;
401 VNInfo::KillSet BKills;
402 std::map<LiveIndex, LiveIndex> BExtend;
404 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
413 // then do not add kills of A to the newly created B interval.
414 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
416 BExtend[ALR->end] = BLR->end;
418 // Update uses of IntA of the specific Val# with IntB.
419 bool BHasSubRegs = false;
420 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
421 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
422 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
423 UE = mri_->use_end(); UI != UE;) {
424 MachineOperand &UseMO = UI.getOperand();
425 MachineInstr *UseMI = &*UI;
427 if (JoinedCopies.count(UseMI))
429 LiveIndex UseIdx= li_->getUseIndex(li_->getInstructionIndex(UseMI));
430 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
431 if (ULR == IntA.end() || ULR->valno != AValNo)
433 UseMO.setReg(NewReg);
436 if (UseMO.isKill()) {
438 UseMO.setIsKill(false);
440 BKills.push_back(li_->getNextSlot(UseIdx));
442 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
443 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
445 if (DstReg == IntB.reg) {
446 // This copy will become a noop. If it's defining a new val#,
447 // remove that val# as well. However this live range is being
448 // extended to the end of the existing live range defined by the copy.
449 LiveIndex DefIdx = li_->getDefIndex(UseIdx);
450 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
451 BHasPHIKill |= DLR->valno->hasPHIKill();
452 assert(DLR->valno->def == DefIdx);
453 BDeadValNos.push_back(DLR->valno);
454 BExtend[DLR->start] = DLR->end;
455 JoinedCopies.insert(UseMI);
456 // If this is a kill but it's going to be removed, the last use
457 // of the same val# is the new kill.
463 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
464 // simply extend BLR if CopyMI doesn't end the range.
466 errs() << "\nExtending: ";
467 IntB.print(errs(), tri_);
470 // Remove val#'s defined by copies that will be coalesced away.
471 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
472 VNInfo *DeadVNI = BDeadValNos[i];
474 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
475 LiveInterval &SRLI = li_->getInterval(*SR);
476 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
477 SRLI.removeValNo(SRLR->valno);
480 IntB.removeValNo(BDeadValNos[i]);
483 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
484 // is updated. Kills are also updated.
485 VNInfo *ValNo = BValNo;
486 ValNo->def = AValNo->def;
488 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
489 if (ValNo->kills[j] != BLR->end)
490 BKills.push_back(ValNo->kills[j]);
492 ValNo->kills.clear();
493 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
495 if (AI->valno != AValNo) continue;
496 LiveIndex End = AI->end;
497 std::map<LiveIndex, LiveIndex>::iterator
498 EI = BExtend.find(End);
499 if (EI != BExtend.end())
501 IntB.addRange(LiveRange(AI->start, End, ValNo));
503 // If the IntB live range is assigned to a physical register, and if that
504 // physreg has sub-registers, update their live intervals as well.
506 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
507 LiveInterval &SRLI = li_->getInterval(*SR);
508 SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
512 IntB.addKills(ValNo, BKills);
513 ValNo->setHasPHIKill(BHasPHIKill);
516 errs() << " result = ";
517 IntB.print(errs(), tri_);
519 errs() << "\nShortening: ";
520 IntA.print(errs(), tri_);
523 IntA.removeValNo(AValNo);
526 errs() << " result = ";
527 IntA.print(errs(), tri_);
535 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
536 /// fallthoughs to SuccMBB.
537 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
538 MachineBasicBlock *SuccMBB,
539 const TargetInstrInfo *tii_) {
542 MachineBasicBlock *TBB = 0, *FBB = 0;
543 SmallVector<MachineOperand, 4> Cond;
544 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
545 MBB->isSuccessor(SuccMBB);
548 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
549 /// from a physical register live interval as well as from the live intervals
550 /// of its sub-registers.
551 static void removeRange(LiveInterval &li,
552 LiveIndex Start, LiveIndex End,
553 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
554 li.removeRange(Start, End, true);
555 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
556 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
557 if (!li_->hasInterval(*SR))
559 LiveInterval &sli = li_->getInterval(*SR);
560 LiveIndex RemoveStart = Start;
561 LiveIndex RemoveEnd = Start;
562 while (RemoveEnd != End) {
563 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
566 RemoveEnd = (LR->end < End) ? LR->end : End;
567 sli.removeRange(RemoveStart, RemoveEnd, true);
568 RemoveStart = RemoveEnd;
574 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
575 /// as the copy instruction, trim the live interval to the last use and return
578 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(LiveIndex CopyIdx,
579 MachineBasicBlock *CopyMBB,
581 const LiveRange *LR) {
582 LiveIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
583 LiveIndex LastUseIdx;
584 MachineOperand *LastUse =
585 lastRegisterUse(LR->start, li_->getPrevSlot(CopyIdx), li.reg, LastUseIdx);
587 MachineInstr *LastUseMI = LastUse->getParent();
588 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
595 // r1025<dead> = r1024<kill>
596 if (MBBStart < LR->end)
597 removeRange(li, MBBStart, LR->end, li_, tri_);
601 // There are uses before the copy, just shorten the live range to the end
603 LastUse->setIsKill();
604 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
605 LR->valno->addKill(li_->getNextSlot(LastUseIdx));
606 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
607 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
609 // Last use is itself an identity code.
610 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
611 LastUseMI->getOperand(DeadIdx).setIsDead();
617 if (LR->start <= MBBStart && LR->end > MBBStart) {
618 if (LR->start == LiveIndex()) {
619 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
620 // Live-in to the function but dead. Remove it from entry live-in set.
621 mf_->begin()->removeLiveIn(li.reg);
623 // FIXME: Shorten intervals in BBs that reaches this BB.
629 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
630 /// computation, replace the copy by rematerialize the definition.
631 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
634 MachineInstr *CopyMI) {
635 LiveIndex CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
636 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
637 assert(SrcLR != SrcInt.end() && "Live range not found!");
638 VNInfo *ValNo = SrcLR->valno;
639 // If other defs can reach uses of this def, then it's not safe to perform
640 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
642 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
643 ValNo->isUnused() || ValNo->hasPHIKill())
645 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
646 const TargetInstrDesc &TID = DefMI->getDesc();
647 if (!TID.isAsCheapAsAMove())
649 if (!DefMI->getDesc().isRematerializable() ||
650 !tii_->isTriviallyReMaterializable(DefMI))
652 bool SawStore = false;
653 if (!DefMI->isSafeToMove(tii_, SawStore))
655 if (TID.getNumDefs() != 1)
657 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
658 // Make sure the copy destination register class fits the instruction
659 // definition register class. The mismatch can happen as a result of earlier
660 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
661 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
662 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
663 if (mri_->getRegClass(DstReg) != RC)
665 } else if (!RC->contains(DstReg))
669 // If destination register has a sub-register index on it, make sure it mtches
670 // the instruction register class.
672 const TargetInstrDesc &TID = DefMI->getDesc();
673 if (TID.getNumDefs() != 1)
675 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
676 const TargetRegisterClass *DstSubRC =
677 DstRC->getSubRegisterRegClass(DstSubIdx);
678 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
681 else if (DefRC != DstSubRC)
685 LiveIndex DefIdx = li_->getDefIndex(CopyIdx);
686 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
687 DLR->valno->setCopy(0);
688 // Don't forget to update sub-register intervals.
689 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
690 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
691 if (!li_->hasInterval(*SR))
693 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
694 if (DLR && DLR->valno->getCopy() == CopyMI)
695 DLR->valno->setCopy(0);
699 // If copy kills the source register, find the last use and propagate
701 bool checkForDeadDef = false;
702 MachineBasicBlock *MBB = CopyMI->getParent();
703 if (CopyMI->killsRegister(SrcInt.reg))
704 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
705 checkForDeadDef = true;
708 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
709 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI);
710 MachineInstr *NewMI = prior(MII);
712 if (checkForDeadDef) {
713 // PR4090 fix: Trim interval failed because there was no use of the
714 // source interval in this MBB. If the def is in this MBB too then we
715 // should mark it dead:
716 if (DefMI->getParent() == MBB) {
717 DefMI->addRegisterDead(SrcInt.reg, tri_);
718 SrcLR->end = li_->getNextSlot(SrcLR->start);
722 // CopyMI may have implicit operands, transfer them over to the newly
723 // rematerialized instruction. And update implicit def interval valnos.
724 for (unsigned i = CopyMI->getDesc().getNumOperands(),
725 e = CopyMI->getNumOperands(); i != e; ++i) {
726 MachineOperand &MO = CopyMI->getOperand(i);
727 if (MO.isReg() && MO.isImplicit())
728 NewMI->addOperand(MO);
729 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
730 unsigned Reg = MO.getReg();
731 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
732 if (DLR && DLR->valno->getCopy() == CopyMI)
733 DLR->valno->setCopy(0);
737 TransferImplicitOps(CopyMI, NewMI);
738 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
739 CopyMI->eraseFromParent();
740 ReMatCopies.insert(CopyMI);
741 ReMatDefs.insert(DefMI);
746 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
747 /// update the subregister number if it is not zero. If DstReg is a
748 /// physical register and the existing subregister number of the def / use
749 /// being updated is not zero, make sure to set it to the correct physical
752 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
754 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
755 if (DstIsPhys && SubIdx) {
756 // Figure out the real physical register we are updating with.
757 DstReg = tri_->getSubReg(DstReg, SubIdx);
761 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
762 E = mri_->reg_end(); I != E; ) {
763 MachineOperand &O = I.getOperand();
764 MachineInstr *UseMI = &*I;
766 unsigned OldSubIdx = O.getSubReg();
768 unsigned UseDstReg = DstReg;
770 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
772 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
773 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
774 CopySrcSubIdx, CopyDstSubIdx) &&
775 CopySrcReg != CopyDstReg &&
776 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
777 // If the use is a copy and it won't be coalesced away, and its source
778 // is defined by a trivial computation, try to rematerialize it instead.
779 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
780 CopyDstSubIdx, UseMI))
789 // Sub-register indexes goes from small to large. e.g.
790 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
791 // EAX: 1 -> AL, 2 -> AX
792 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
793 // sub-register 2 is also AX.
794 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
795 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
798 // Remove would-be duplicated kill marker.
799 if (O.isKill() && UseMI->killsRegister(DstReg))
803 // After updating the operand, check if the machine instruction has
804 // become a copy. If so, update its val# information.
805 if (JoinedCopies.count(UseMI))
808 const TargetInstrDesc &TID = UseMI->getDesc();
809 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
810 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
811 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
812 CopySrcSubIdx, CopyDstSubIdx) &&
813 CopySrcReg != CopyDstReg &&
814 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
815 allocatableRegs_[CopyDstReg])) {
816 LiveInterval &LI = li_->getInterval(CopyDstReg);
818 li_->getDefIndex(li_->getInstructionIndex(UseMI));
819 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
820 if (DLR->valno->def == DefIdx)
821 DLR->valno->setCopy(UseMI);
827 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
828 /// due to live range lengthening as the result of coalescing.
829 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
831 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
832 UE = mri_->use_end(); UI != UE; ++UI) {
833 MachineOperand &UseMO = UI.getOperand();
836 MachineInstr *UseMI = UseMO.getParent();
838 li_->getUseIndex(li_->getInstructionIndex(UseMI));
839 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
841 (!LR->valno->isKill(li_->getNextSlot(UseIdx)) &&
842 LR->valno->def != li_->getNextSlot(UseIdx))) {
843 // Interesting problem. After coalescing reg1027's def and kill are both
844 // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814)
847 // 60 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
848 // 68 %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
849 // 76 t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
850 // 84 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
851 // 96 t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
853 // Do not remove the kill marker on t2LDRi12.
854 UseMO.setIsKill(false);
859 /// removeIntervalIfEmpty - Check if the live interval of a physical register
860 /// is empty, if so remove it and also remove the empty intervals of its
861 /// sub-registers. Return true if live interval is removed.
862 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
863 const TargetRegisterInfo *tri_) {
865 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
866 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
867 if (!li_->hasInterval(*SR))
869 LiveInterval &sli = li_->getInterval(*SR);
871 li_->removeInterval(*SR);
873 li_->removeInterval(li.reg);
879 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
880 /// Return true if live interval is removed.
881 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
882 MachineInstr *CopyMI) {
883 LiveIndex CopyIdx = li_->getInstructionIndex(CopyMI);
884 LiveInterval::iterator MLR =
885 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
887 return false; // Already removed by ShortenDeadCopySrcLiveRange.
888 LiveIndex RemoveStart = MLR->start;
889 LiveIndex RemoveEnd = MLR->end;
890 LiveIndex DefIdx = li_->getDefIndex(CopyIdx);
891 // Remove the liverange that's defined by this.
892 if (RemoveStart == DefIdx && RemoveEnd == li_->getNextSlot(DefIdx)) {
893 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
894 return removeIntervalIfEmpty(li, li_, tri_);
899 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
900 /// the val# it defines. If the live interval becomes empty, remove it as well.
901 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
902 MachineInstr *DefMI) {
903 LiveIndex DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
904 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
905 if (DefIdx != MLR->valno->def)
907 li.removeValNo(MLR->valno);
908 return removeIntervalIfEmpty(li, li_, tri_);
911 /// PropagateDeadness - Propagate the dead marker to the instruction which
912 /// defines the val#.
913 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
914 LiveIndex &LRStart, LiveIntervals *li_,
915 const TargetRegisterInfo* tri_) {
916 MachineInstr *DefMI =
917 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
918 if (DefMI && DefMI != CopyMI) {
919 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
921 DefMI->getOperand(DeadIdx).setIsDead();
923 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
924 true, true, false, true));
925 LRStart = li_->getNextSlot(LRStart);
929 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
930 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
931 /// ends the live range there. If there isn't another use, then this live range
932 /// is dead. Return true if live interval is removed.
934 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
935 MachineInstr *CopyMI) {
936 LiveIndex CopyIdx = li_->getInstructionIndex(CopyMI);
937 if (CopyIdx == LiveIndex()) {
938 // FIXME: special case: function live in. It can be a general case if the
939 // first instruction index starts at > 0 value.
940 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
941 // Live-in to the function but dead. Remove it from entry live-in set.
942 if (mf_->begin()->isLiveIn(li.reg))
943 mf_->begin()->removeLiveIn(li.reg);
944 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
945 removeRange(li, LR->start, LR->end, li_, tri_);
946 return removeIntervalIfEmpty(li, li_, tri_);
949 LiveInterval::iterator LR =
950 li.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
952 // Livein but defined by a phi.
955 LiveIndex RemoveStart = LR->start;
956 LiveIndex RemoveEnd = li_->getNextSlot(li_->getDefIndex(CopyIdx));
957 if (LR->end > RemoveEnd)
958 // More uses past this copy? Nothing to do.
961 // If there is a last use in the same bb, we can't remove the live range.
962 // Shorten the live interval and return.
963 MachineBasicBlock *CopyMBB = CopyMI->getParent();
964 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
967 // There are other kills of the val#. Nothing to do.
968 if (!li.isOnlyLROfValNo(LR))
971 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
972 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
973 // If the live range starts in another mbb and the copy mbb is not a fall
974 // through mbb, then we can only cut the range from the beginning of the
976 RemoveStart = li_->getNextSlot(li_->getMBBStartIdx(CopyMBB));
978 if (LR->valno->def == RemoveStart) {
979 // If the def MI defines the val# and this copy is the only kill of the
980 // val#, then propagate the dead marker.
981 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
984 if (LR->valno->isKill(RemoveEnd))
985 LR->valno->removeKill(RemoveEnd);
988 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
989 return removeIntervalIfEmpty(li, li_, tri_);
992 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
993 /// from an implicit def to another register can be coalesced away.
994 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
996 LiveInterval &ImpLi) const{
997 if (!CopyMI->killsRegister(ImpLi.reg))
999 // Make sure this is the only use.
1000 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1001 UE = mri_->use_end(); UI != UE;) {
1002 MachineInstr *UseMI = &*UI;
1004 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1012 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1013 /// a virtual destination register with physical source register.
1015 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1016 MachineBasicBlock *CopyMBB,
1017 LiveInterval &DstInt,
1018 LiveInterval &SrcInt) {
1019 // If the virtual register live interval is long but it has low use desity,
1020 // do not join them, instead mark the physical register as its allocation
1022 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1023 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1024 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1025 if (Length > Threshold &&
1026 (((float)std::distance(mri_->use_begin(DstInt.reg),
1027 mri_->use_end()) / Length) < (1.0 / Threshold)))
1030 // If the virtual register live interval extends into a loop, turn down
1033 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1034 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1036 // Let's see if the virtual register live interval extends into the loop.
1037 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1038 assert(DLR != DstInt.end() && "Live range not found!");
1039 DLR = DstInt.FindLiveRangeContaining(li_->getNextSlot(DLR->end));
1040 if (DLR != DstInt.end()) {
1041 CopyMBB = li_->getMBBFromIndex(DLR->start);
1042 L = loopInfo->getLoopFor(CopyMBB);
1046 if (!L || Length <= Threshold)
1049 LiveIndex UseIdx = li_->getUseIndex(CopyIdx);
1050 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1051 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1052 if (loopInfo->getLoopFor(SMBB) != L) {
1053 if (!loopInfo->isLoopHeader(CopyMBB))
1055 // If vr's live interval extends pass the loop header, do not join.
1056 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1057 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1058 MachineBasicBlock *SuccMBB = *SI;
1059 if (SuccMBB == CopyMBB)
1061 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1062 li_->getNextSlot(li_->getMBBEndIdx(SuccMBB))))
1069 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1070 /// copy from a virtual source register to a physical destination register.
1072 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1073 MachineBasicBlock *CopyMBB,
1074 LiveInterval &DstInt,
1075 LiveInterval &SrcInt) {
1076 // If the virtual register live interval is long but it has low use desity,
1077 // do not join them, instead mark the physical register as its allocation
1079 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1080 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1081 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1082 if (Length > Threshold &&
1083 (((float)std::distance(mri_->use_begin(SrcInt.reg),
1084 mri_->use_end()) / Length) < (1.0 / Threshold)))
1088 // Must be implicit_def.
1091 // If the virtual register live interval is defined or cross a loop, turn
1092 // down aggressiveness.
1094 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1095 LiveIndex UseIdx = li_->getUseIndex(CopyIdx);
1096 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1097 assert(SLR != SrcInt.end() && "Live range not found!");
1098 SLR = SrcInt.FindLiveRangeContaining(li_->getPrevSlot(SLR->start));
1099 if (SLR == SrcInt.end())
1101 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1102 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1104 if (!L || Length <= Threshold)
1107 if (loopInfo->getLoopFor(CopyMBB) != L) {
1108 if (SMBB != L->getLoopLatch())
1110 // If vr's live interval is extended from before the loop latch, do not
1112 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1113 PE = SMBB->pred_end(); PI != PE; ++PI) {
1114 MachineBasicBlock *PredMBB = *PI;
1115 if (PredMBB == SMBB)
1117 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1118 li_->getNextSlot(li_->getMBBEndIdx(PredMBB))))
1125 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1126 /// two virtual registers from different register classes.
1128 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1130 unsigned Threshold) {
1131 // Then make sure the intervals are *short*.
1132 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1133 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1134 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1135 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1136 if (SmallSize > Threshold || LargeSize > Threshold)
1137 if ((float)std::distance(mri_->use_begin(SmallReg),
1138 mri_->use_end()) / SmallSize <
1139 (float)std::distance(mri_->use_begin(LargeReg),
1140 mri_->use_end()) / LargeSize)
1145 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1146 /// register with a physical register, check if any of the virtual register
1147 /// operand is a sub-register use or def. If so, make sure it won't result
1148 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1149 /// vr1024 = extract_subreg vr1025, 1
1151 /// vr1024 = mov8rr AH
1152 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1153 /// AH does not have a super-reg whose sub-register 1 is AH.
1155 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1158 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1159 E = mri_->reg_end(); I != E; ++I) {
1160 MachineOperand &O = I.getOperand();
1161 MachineInstr *MI = &*I;
1162 if (MI == CopyMI || JoinedCopies.count(MI))
1164 unsigned SubIdx = O.getSubReg();
1165 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1167 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1168 SubIdx = MI->getOperand(2).getImm();
1169 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1172 unsigned SrcReg = MI->getOperand(1).getReg();
1173 const TargetRegisterClass *RC =
1174 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1175 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1176 : mri_->getRegClass(SrcReg);
1177 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1181 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1182 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
1183 SubIdx = MI->getOperand(3).getImm();
1184 if (VirtReg == MI->getOperand(0).getReg()) {
1185 if (!tri_->getSubReg(PhysReg, SubIdx))
1188 unsigned DstReg = MI->getOperand(0).getReg();
1189 const TargetRegisterClass *RC =
1190 TargetRegisterInfo::isPhysicalRegister(DstReg)
1191 ? tri_->getPhysicalRegisterRegClass(DstReg)
1192 : mri_->getRegClass(DstReg);
1193 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1202 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1203 /// an extract_subreg where dst is a physical register, e.g.
1204 /// cl = EXTRACT_SUBREG reg1024, 1
1206 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1207 unsigned SrcReg, unsigned SubIdx,
1208 unsigned &RealDstReg) {
1209 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1210 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1211 assert(RealDstReg && "Invalid extract_subreg instruction!");
1213 // For this type of EXTRACT_SUBREG, conservatively
1214 // check if the live interval of the source register interfere with the
1215 // actual super physical register we are trying to coalesce with.
1216 LiveInterval &RHS = li_->getInterval(SrcReg);
1217 if (li_->hasInterval(RealDstReg) &&
1218 RHS.overlaps(li_->getInterval(RealDstReg))) {
1220 errs() << "Interfere with register ";
1221 li_->getInterval(RealDstReg).print(errs(), tri_);
1223 return false; // Not coalescable
1225 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1226 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1228 errs() << "Interfere with sub-register ";
1229 li_->getInterval(*SR).print(errs(), tri_);
1231 return false; // Not coalescable
1236 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1237 /// an insert_subreg where src is a physical register, e.g.
1238 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1240 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1241 unsigned SrcReg, unsigned SubIdx,
1242 unsigned &RealSrcReg) {
1243 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1244 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1245 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1247 LiveInterval &RHS = li_->getInterval(DstReg);
1248 if (li_->hasInterval(RealSrcReg) &&
1249 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1251 errs() << "Interfere with register ";
1252 li_->getInterval(RealSrcReg).print(errs(), tri_);
1254 return false; // Not coalescable
1256 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1257 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1259 errs() << "Interfere with sub-register ";
1260 li_->getInterval(*SR).print(errs(), tri_);
1262 return false; // Not coalescable
1267 /// getRegAllocPreference - Return register allocation preference register.
1269 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1270 MachineRegisterInfo *MRI,
1271 const TargetRegisterInfo *TRI) {
1272 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1274 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1275 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1278 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1279 /// which are the src/dst of the copy instruction CopyMI. This returns true
1280 /// if the copy was successfully coalesced away. If it is not currently
1281 /// possible to coalesce this interval, but it may be possible if other
1282 /// things get coalesced, then it returns true by reference in 'Again'.
1283 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1284 MachineInstr *CopyMI = TheCopy.MI;
1287 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1288 return false; // Already done.
1290 DEBUG(errs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1292 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1293 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1294 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1295 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
1296 unsigned SubIdx = 0;
1298 DstReg = CopyMI->getOperand(0).getReg();
1299 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1300 SrcReg = CopyMI->getOperand(1).getReg();
1301 SrcSubIdx = CopyMI->getOperand(2).getImm();
1302 } else if (isInsSubReg || isSubRegToReg) {
1303 DstReg = CopyMI->getOperand(0).getReg();
1304 DstSubIdx = CopyMI->getOperand(3).getImm();
1305 SrcReg = CopyMI->getOperand(2).getReg();
1306 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1307 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1308 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1309 // coalesced to a larger register so the subreg indices cancel out.
1310 DEBUG(errs() << "\tSource of insert_subreg or subreg_to_reg is already "
1311 "coalesced to another register.\n");
1312 return false; // Not coalescable.
1314 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1315 llvm_unreachable("Unrecognized copy instruction!");
1318 // If they are already joined we continue.
1319 if (SrcReg == DstReg) {
1320 DEBUG(errs() << "\tCopy already coalesced.\n");
1321 return false; // Not coalescable.
1324 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1325 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1327 // If they are both physical registers, we cannot join them.
1328 if (SrcIsPhys && DstIsPhys) {
1329 DEBUG(errs() << "\tCan not coalesce physregs.\n");
1330 return false; // Not coalescable.
1333 // We only join virtual registers with allocatable physical registers.
1334 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1335 DEBUG(errs() << "\tSrc reg is unallocatable physreg.\n");
1336 return false; // Not coalescable.
1338 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1339 DEBUG(errs() << "\tDst reg is unallocatable physreg.\n");
1340 return false; // Not coalescable.
1343 // Check that a physical source register is compatible with dst regclass
1345 unsigned SrcSubReg = SrcSubIdx ?
1346 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1347 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1348 const TargetRegisterClass *DstSubRC = DstRC;
1350 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1351 assert(DstSubRC && "Illegal subregister index");
1352 if (!DstSubRC->contains(SrcSubReg)) {
1353 DEBUG(errs() << "\tIncompatible destination regclass: "
1354 << tri_->getName(SrcSubReg) << " not in "
1355 << DstSubRC->getName() << ".\n");
1356 return false; // Not coalescable.
1360 // Check that a physical dst register is compatible with source regclass
1362 unsigned DstSubReg = DstSubIdx ?
1363 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1364 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1365 const TargetRegisterClass *SrcSubRC = SrcRC;
1367 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1368 assert(SrcSubRC && "Illegal subregister index");
1369 if (!SrcSubRC->contains(DstReg)) {
1370 DEBUG(errs() << "\tIncompatible source regclass: "
1371 << tri_->getName(DstSubReg) << " not in "
1372 << SrcSubRC->getName() << ".\n");
1374 return false; // Not coalescable.
1378 // Should be non-null only when coalescing to a sub-register class.
1379 bool CrossRC = false;
1380 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1381 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1382 const TargetRegisterClass *NewRC = NULL;
1383 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1384 unsigned RealDstReg = 0;
1385 unsigned RealSrcReg = 0;
1386 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1387 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1388 if (SrcIsPhys && isExtSubReg) {
1389 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1390 // coalesced with AX.
1391 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1393 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1394 // coalesced to a larger register so the subreg indices cancel out.
1395 if (DstSubIdx != SubIdx) {
1396 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1397 return false; // Not coalescable.
1400 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1402 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1403 // EAX = INSERT_SUBREG EAX, r1024, 0
1404 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1406 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1407 // coalesced to a larger register so the subreg indices cancel out.
1408 if (SrcSubIdx != SubIdx) {
1409 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1410 return false; // Not coalescable.
1413 DstReg = tri_->getSubReg(DstReg, SubIdx);
1415 } else if ((DstIsPhys && isExtSubReg) ||
1416 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1417 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1418 DEBUG(errs() << "\tSrc of extract_subreg already coalesced with reg"
1419 << " of a super-class.\n");
1420 return false; // Not coalescable.
1424 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1425 return false; // Not coalescable
1427 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1428 return false; // Not coalescable
1432 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1433 : CopyMI->getOperand(2).getSubReg();
1435 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1436 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1437 // coalesced to a larger register so the subreg indices cancel out.
1438 // Also check if the other larger register is of the same register
1439 // class as the would be resulting register.
1442 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1443 return false; // Not coalescable.
1447 if (!DstIsPhys && !SrcIsPhys) {
1448 if (isInsSubReg || isSubRegToReg) {
1449 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1450 } else // extract_subreg {
1451 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1454 DEBUG(errs() << "\t Conflicting sub-register indices.\n");
1455 return false; // Not coalescable
1458 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1459 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1460 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1461 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1462 Again = true; // May be possible to coalesce later.
1467 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1468 if (DisableCrossClassJoin)
1472 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1473 // with another? If it's the resulting destination register, then
1474 // the subidx must be propagated to uses (but only those defined
1475 // by the EXTRACT_SUBREG). If it's being coalesced into another
1476 // register, it should be safe because register is assumed to have
1477 // the register class of the super-register.
1479 // Process moves where one of the registers have a sub-register index.
1480 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1481 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1482 SubIdx = DstMO->getSubReg();
1484 if (SrcMO->getSubReg())
1485 // FIXME: can we handle this?
1487 // This is not an insert_subreg but it looks like one.
1488 // e.g. %reg1024:4 = MOV32rr %EAX
1491 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1492 return false; // Not coalescable
1496 SubIdx = SrcMO->getSubReg();
1498 // This is not a extract_subreg but it looks like one.
1499 // e.g. %cl = MOV16rr %reg1024:1
1502 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1503 return false; // Not coalescable
1509 unsigned LargeReg = SrcReg;
1510 unsigned SmallReg = DstReg;
1512 // Now determine the register class of the joined register.
1514 if (SubIdx && DstRC && DstRC->isASubClass()) {
1515 // This is a move to a sub-register class. However, the source is a
1516 // sub-register of a larger register class. We don't know what should
1517 // the register class be. FIXME.
1521 if (!DstIsPhys && !SrcIsPhys)
1523 } else if (!SrcIsPhys && !DstIsPhys) {
1524 NewRC = getCommonSubClass(SrcRC, DstRC);
1526 DEBUG(errs() << "\tDisjoint regclasses: "
1527 << SrcRC->getName() << ", "
1528 << DstRC->getName() << ".\n");
1529 return false; // Not coalescable.
1531 if (DstRC->getSize() > SrcRC->getSize())
1532 std::swap(LargeReg, SmallReg);
1535 // If we are joining two virtual registers and the resulting register
1536 // class is more restrictive (fewer register, smaller size). Check if it's
1537 // worth doing the merge.
1538 if (!SrcIsPhys && !DstIsPhys &&
1539 (isExtSubReg || DstRC->isASubClass()) &&
1540 !isWinToJoinCrossClass(LargeReg, SmallReg,
1541 allocatableRCRegs_[NewRC].count())) {
1542 DEBUG(errs() << "\tSrc/Dest are different register classes.\n");
1543 // Allow the coalescer to try again in case either side gets coalesced to
1544 // a physical register that's compatible with the other side. e.g.
1545 // r1024 = MOV32to32_ r1025
1546 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1547 Again = true; // May be possible to coalesce later.
1552 // Will it create illegal extract_subreg / insert_subreg?
1553 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1555 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1558 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1559 LiveInterval &DstInt = li_->getInterval(DstReg);
1560 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1561 "Register mapping is horribly broken!");
1564 errs() << "\t\tInspecting "; SrcInt.print(errs(), tri_);
1565 errs() << " and "; DstInt.print(errs(), tri_);
1569 // Save a copy of the virtual register live interval. We'll manually
1570 // merge this into the "real" physical register live interval this is
1572 LiveInterval *SavedLI = 0;
1574 SavedLI = li_->dupInterval(&SrcInt);
1575 else if (RealSrcReg)
1576 SavedLI = li_->dupInterval(&DstInt);
1578 // Check if it is necessary to propagate "isDead" property.
1579 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1580 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1581 bool isDead = mopd->isDead();
1583 // We need to be careful about coalescing a source physical register with a
1584 // virtual register. Once the coalescing is done, it cannot be broken and
1585 // these are not spillable! If the destination interval uses are far away,
1586 // think twice about coalescing them!
1587 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1588 // If the copy is in a loop, take care not to coalesce aggressively if the
1589 // src is coming in from outside the loop (or the dst is out of the loop).
1590 // If it's not in a loop, then determine whether to join them base purely
1591 // by the length of the interval.
1592 if (PhysJoinTweak) {
1594 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1595 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1597 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1598 Again = true; // May be possible to coalesce later.
1602 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1603 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1605 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1606 Again = true; // May be possible to coalesce later.
1611 // If the virtual register live interval is long but it has low use desity,
1612 // do not join them, instead mark the physical register as its allocation
1614 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1615 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1616 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1617 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1618 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1619 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1620 float Ratio = 1.0 / Threshold;
1621 if (Length > Threshold &&
1622 (((float)std::distance(mri_->use_begin(JoinVReg),
1623 mri_->use_end()) / Length) < Ratio)) {
1624 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1626 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1627 Again = true; // May be possible to coalesce later.
1634 // Okay, attempt to join these two intervals. On failure, this returns false.
1635 // Otherwise, if one of the intervals being joined is a physreg, this method
1636 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1637 // been modified, so we can use this information below to update aliases.
1638 bool Swapped = false;
1639 // If SrcInt is implicitly defined, it's safe to coalesce.
1640 bool isEmpty = SrcInt.empty();
1641 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1642 // Only coalesce an empty interval (defined by implicit_def) with
1643 // another interval which has a valno defined by the CopyMI and the CopyMI
1644 // is a kill of the implicit def.
1645 DEBUG(errs() << "Not profitable!\n");
1649 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1650 // Coalescing failed.
1652 // If definition of source is defined by trivial computation, try
1653 // rematerializing it.
1654 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1655 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1658 // If we can eliminate the copy without merging the live ranges, do so now.
1659 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1660 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1661 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1662 JoinedCopies.insert(CopyMI);
1666 // Otherwise, we are unable to join the intervals.
1667 DEBUG(errs() << "Interference!\n");
1668 Again = true; // May be possible to coalesce later.
1672 LiveInterval *ResSrcInt = &SrcInt;
1673 LiveInterval *ResDstInt = &DstInt;
1675 std::swap(SrcReg, DstReg);
1676 std::swap(ResSrcInt, ResDstInt);
1678 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1679 "LiveInterval::join didn't work right!");
1681 // If we're about to merge live ranges into a physical register live interval,
1682 // we have to update any aliased register's live ranges to indicate that they
1683 // have clobbered values for this range.
1684 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1685 // If this is a extract_subreg where dst is a physical register, e.g.
1686 // cl = EXTRACT_SUBREG reg1024, 1
1687 // then create and update the actual physical register allocated to RHS.
1688 if (RealDstReg || RealSrcReg) {
1689 LiveInterval &RealInt =
1690 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1691 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1692 E = SavedLI->vni_end(); I != E; ++I) {
1693 const VNInfo *ValNo = *I;
1694 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1695 false, // updated at *
1696 li_->getVNInfoAllocator());
1697 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1698 RealInt.addKills(NewValNo, ValNo->kills);
1699 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1701 RealInt.weight += SavedLI->weight;
1702 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1705 // Update the liveintervals of sub-registers.
1706 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1707 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1708 li_->getVNInfoAllocator());
1711 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1712 // larger super-register.
1713 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1714 !SrcIsPhys && !DstIsPhys) {
1715 if ((isExtSubReg && !Swapped) ||
1716 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1717 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1718 std::swap(SrcReg, DstReg);
1719 std::swap(ResSrcInt, ResDstInt);
1723 // Coalescing to a virtual register that is of a sub-register class of the
1724 // other. Make sure the resulting register is set to the right register class.
1728 // This may happen even if it's cross-rc coalescing. e.g.
1729 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1730 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1731 // be allocate a register from GR64_ABCD.
1733 mri_->setRegClass(DstReg, NewRC);
1735 // Remember to delete the copy instruction.
1736 JoinedCopies.insert(CopyMI);
1738 // Some live range has been lengthened due to colaescing, eliminate the
1739 // unnecessary kills.
1740 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1741 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1742 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1744 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1746 // SrcReg is guarateed to be the register whose live interval that is
1748 li_->removeInterval(SrcReg);
1750 // Update regalloc hint.
1751 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1753 // Manually deleted the live interval copy.
1759 // If resulting interval has a preference that no longer fits because of subreg
1760 // coalescing, just clear the preference.
1761 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1762 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1763 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1764 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1765 if (!RC->contains(Preference))
1766 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1770 errs() << "\n\t\tJoined. Result = ";
1771 ResDstInt->print(errs(), tri_);
1779 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1780 /// compute what the resultant value numbers for each value in the input two
1781 /// ranges will be. This is complicated by copies between the two which can
1782 /// and will commonly cause multiple value numbers to be merged into one.
1784 /// VN is the value number that we're trying to resolve. InstDefiningValue
1785 /// keeps track of the new InstDefiningValue assignment for the result
1786 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1787 /// whether a value in this or other is a copy from the opposite set.
1788 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1789 /// already been assigned.
1791 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1792 /// contains the value number the copy is from.
1794 static unsigned ComputeUltimateVN(VNInfo *VNI,
1795 SmallVector<VNInfo*, 16> &NewVNInfo,
1796 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1797 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1798 SmallVector<int, 16> &ThisValNoAssignments,
1799 SmallVector<int, 16> &OtherValNoAssignments) {
1800 unsigned VN = VNI->id;
1802 // If the VN has already been computed, just return it.
1803 if (ThisValNoAssignments[VN] >= 0)
1804 return ThisValNoAssignments[VN];
1805 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1807 // If this val is not a copy from the other val, then it must be a new value
1808 // number in the destination.
1809 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1810 if (I == ThisFromOther.end()) {
1811 NewVNInfo.push_back(VNI);
1812 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1814 VNInfo *OtherValNo = I->second;
1816 // Otherwise, this *is* a copy from the RHS. If the other side has already
1817 // been computed, return it.
1818 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1819 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1821 // Mark this value number as currently being computed, then ask what the
1822 // ultimate value # of the other value is.
1823 ThisValNoAssignments[VN] = -2;
1824 unsigned UltimateVN =
1825 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1826 OtherValNoAssignments, ThisValNoAssignments);
1827 return ThisValNoAssignments[VN] = UltimateVN;
1830 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1831 return std::find(V.begin(), V.end(), Val) != V.end();
1834 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1835 /// the specified live interval is defined by a copy from the specified
1837 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1840 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1843 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1844 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1845 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1846 *tri_->getSuperRegisters(li.reg)) {
1847 // It's a sub-register live interval, we may not have precise information.
1849 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1850 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1852 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1853 DstReg == li.reg && SrcReg == Reg) {
1854 // Cache computed info.
1855 LR->valno->def = LR->start;
1856 LR->valno->setCopy(DefMI);
1863 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1864 /// caller of this method must guarantee that the RHS only contains a single
1865 /// value number and that the RHS is not defined by a copy from this
1866 /// interval. This returns false if the intervals are not joinable, or it
1867 /// joins them and returns true.
1868 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1869 assert(RHS.containsOneValue());
1871 // Some number (potentially more than one) value numbers in the current
1872 // interval may be defined as copies from the RHS. Scan the overlapping
1873 // portions of the LHS and RHS, keeping track of this and looking for
1874 // overlapping live ranges that are NOT defined as copies. If these exist, we
1877 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1878 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1880 if (LHSIt->start < RHSIt->start) {
1881 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1882 if (LHSIt != LHS.begin()) --LHSIt;
1883 } else if (RHSIt->start < LHSIt->start) {
1884 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1885 if (RHSIt != RHS.begin()) --RHSIt;
1888 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1891 // Determine if these live intervals overlap.
1892 bool Overlaps = false;
1893 if (LHSIt->start <= RHSIt->start)
1894 Overlaps = LHSIt->end > RHSIt->start;
1896 Overlaps = RHSIt->end > LHSIt->start;
1898 // If the live intervals overlap, there are two interesting cases: if the
1899 // LHS interval is defined by a copy from the RHS, it's ok and we record
1900 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1901 // coalesce these live ranges and we bail out.
1903 // If we haven't already recorded that this value # is safe, check it.
1904 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1905 // Copy from the RHS?
1906 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1907 return false; // Nope, bail out.
1909 if (LHSIt->contains(RHSIt->valno->def))
1910 // Here is an interesting situation:
1912 // vr1025 = copy vr1024
1917 // Even though vr1025 is copied from vr1024, it's not safe to
1918 // coalesce them since the live range of vr1025 intersects the
1919 // def of vr1024. This happens because vr1025 is assigned the
1920 // value of the previous iteration of vr1024.
1922 EliminatedLHSVals.push_back(LHSIt->valno);
1925 // We know this entire LHS live range is okay, so skip it now.
1926 if (++LHSIt == LHSEnd) break;
1930 if (LHSIt->end < RHSIt->end) {
1931 if (++LHSIt == LHSEnd) break;
1933 // One interesting case to check here. It's possible that we have
1934 // something like "X3 = Y" which defines a new value number in the LHS,
1935 // and is the last use of this liverange of the RHS. In this case, we
1936 // want to notice this copy (so that it gets coalesced away) even though
1937 // the live ranges don't actually overlap.
1938 if (LHSIt->start == RHSIt->end) {
1939 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1940 // We already know that this value number is going to be merged in
1941 // if coalescing succeeds. Just skip the liverange.
1942 if (++LHSIt == LHSEnd) break;
1944 // Otherwise, if this is a copy from the RHS, mark it as being merged
1946 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1947 if (LHSIt->contains(RHSIt->valno->def))
1948 // Here is an interesting situation:
1950 // vr1025 = copy vr1024
1955 // Even though vr1025 is copied from vr1024, it's not safe to
1956 // coalesced them since live range of vr1025 intersects the
1957 // def of vr1024. This happens because vr1025 is assigned the
1958 // value of the previous iteration of vr1024.
1960 EliminatedLHSVals.push_back(LHSIt->valno);
1962 // We know this entire LHS live range is okay, so skip it now.
1963 if (++LHSIt == LHSEnd) break;
1968 if (++RHSIt == RHSEnd) break;
1972 // If we got here, we know that the coalescing will be successful and that
1973 // the value numbers in EliminatedLHSVals will all be merged together. Since
1974 // the most common case is that EliminatedLHSVals has a single number, we
1975 // optimize for it: if there is more than one value, we merge them all into
1976 // the lowest numbered one, then handle the interval as if we were merging
1977 // with one value number.
1978 VNInfo *LHSValNo = NULL;
1979 if (EliminatedLHSVals.size() > 1) {
1980 // Loop through all the equal value numbers merging them into the smallest
1982 VNInfo *Smallest = EliminatedLHSVals[0];
1983 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1984 if (EliminatedLHSVals[i]->id < Smallest->id) {
1985 // Merge the current notion of the smallest into the smaller one.
1986 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1987 Smallest = EliminatedLHSVals[i];
1989 // Merge into the smallest.
1990 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1993 LHSValNo = Smallest;
1994 } else if (EliminatedLHSVals.empty()) {
1995 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1996 *tri_->getSuperRegisters(LHS.reg))
1997 // Imprecise sub-register information. Can't handle it.
1999 llvm_unreachable("No copies from the RHS?");
2001 LHSValNo = EliminatedLHSVals[0];
2004 // Okay, now that there is a single LHS value number that we're merging the
2005 // RHS into, update the value number info for the LHS to indicate that the
2006 // value number is defined where the RHS value number was.
2007 const VNInfo *VNI = RHS.getValNumInfo(0);
2008 LHSValNo->def = VNI->def;
2009 LHSValNo->setCopy(VNI->getCopy());
2011 // Okay, the final step is to loop over the RHS live intervals, adding them to
2013 if (VNI->hasPHIKill())
2014 LHSValNo->setHasPHIKill(true);
2015 LHS.addKills(LHSValNo, VNI->kills);
2016 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2018 LHS.ComputeJoinedWeight(RHS);
2020 // Update regalloc hint if both are virtual registers.
2021 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2022 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2023 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2024 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2025 if (RHSPref != LHSPref)
2026 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2029 // Update the liveintervals of sub-registers.
2030 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2031 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2032 li_->getOrCreateInterval(*AS).MergeInClobberRanges(LHS,
2033 li_->getVNInfoAllocator());
2038 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2039 /// returns false. Otherwise, if one of the intervals being joined is a
2040 /// physreg, this method always canonicalizes LHS to be it. The output
2041 /// "RHS" will not have been modified, so we can use this information
2042 /// below to update aliases.
2044 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2046 // Compute the final value assignment, assuming that the live ranges can be
2048 SmallVector<int, 16> LHSValNoAssignments;
2049 SmallVector<int, 16> RHSValNoAssignments;
2050 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2051 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2052 SmallVector<VNInfo*, 16> NewVNInfo;
2054 // If a live interval is a physical register, conservatively check if any
2055 // of its sub-registers is overlapping the live interval of the virtual
2056 // register. If so, do not coalesce.
2057 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2058 *tri_->getSubRegisters(LHS.reg)) {
2059 // If it's coalescing a virtual register to a physical register, estimate
2060 // its live interval length. This is the *cost* of scanning an entire live
2061 // interval. If the cost is low, we'll do an exhaustive check instead.
2063 // If this is something like this:
2071 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2072 // less conservative check. It's possible a sub-register is defined before
2073 // v1024 (or live in) and live out of BB1.
2074 if (RHS.containsOneValue() &&
2075 li_->intervalIsInOneMBB(RHS) &&
2076 li_->getApproximateInstructionCount(RHS) <= 10) {
2077 // Perform a more exhaustive check for some common cases.
2078 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2081 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2082 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2084 errs() << "Interfere with sub-register ";
2085 li_->getInterval(*SR).print(errs(), tri_);
2090 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2091 *tri_->getSubRegisters(RHS.reg)) {
2092 if (LHS.containsOneValue() &&
2093 li_->getApproximateInstructionCount(LHS) <= 10) {
2094 // Perform a more exhaustive check for some common cases.
2095 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2098 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2099 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2101 errs() << "Interfere with sub-register ";
2102 li_->getInterval(*SR).print(errs(), tri_);
2109 // Compute ultimate value numbers for the LHS and RHS values.
2110 if (RHS.containsOneValue()) {
2111 // Copies from a liveinterval with a single value are simple to handle and
2112 // very common, handle the special case here. This is important, because
2113 // often RHS is small and LHS is large (e.g. a physreg).
2115 // Find out if the RHS is defined as a copy from some value in the LHS.
2116 int RHSVal0DefinedFromLHS = -1;
2118 VNInfo *RHSValNoInfo = NULL;
2119 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2120 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2121 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2122 // If RHS is not defined as a copy from the LHS, we can use simpler and
2123 // faster checks to see if the live ranges are coalescable. This joiner
2124 // can't swap the LHS/RHS intervals though.
2125 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2126 return SimpleJoin(LHS, RHS);
2128 RHSValNoInfo = RHSValNoInfo0;
2131 // It was defined as a copy from the LHS, find out what value # it is.
2133 LHS.getLiveRangeContaining(li_->getPrevSlot(RHSValNoInfo0->def))->valno;
2134 RHSValID = RHSValNoInfo->id;
2135 RHSVal0DefinedFromLHS = RHSValID;
2138 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2139 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2140 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2142 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2143 // should now get updated.
2144 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2147 unsigned VN = VNI->id;
2148 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2149 if (LHSSrcReg != RHS.reg) {
2150 // If this is not a copy from the RHS, its value number will be
2151 // unmodified by the coalescing.
2152 NewVNInfo[VN] = VNI;
2153 LHSValNoAssignments[VN] = VN;
2154 } else if (RHSValID == -1) {
2155 // Otherwise, it is a copy from the RHS, and we don't already have a
2156 // value# for it. Keep the current value number, but remember it.
2157 LHSValNoAssignments[VN] = RHSValID = VN;
2158 NewVNInfo[VN] = RHSValNoInfo;
2159 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2161 // Otherwise, use the specified value #.
2162 LHSValNoAssignments[VN] = RHSValID;
2163 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2164 NewVNInfo[VN] = RHSValNoInfo;
2165 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2169 NewVNInfo[VN] = VNI;
2170 LHSValNoAssignments[VN] = VN;
2174 assert(RHSValID != -1 && "Didn't find value #?");
2175 RHSValNoAssignments[0] = RHSValID;
2176 if (RHSVal0DefinedFromLHS != -1) {
2177 // This path doesn't go through ComputeUltimateVN so just set
2179 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2182 // Loop over the value numbers of the LHS, seeing if any are defined from
2184 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2187 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2190 // DstReg is known to be a register in the LHS interval. If the src is
2191 // from the RHS interval, we can use its value #.
2192 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2195 // Figure out the value # from the RHS.
2196 LHSValsDefinedFromRHS[VNI]=
2197 RHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2200 // Loop over the value numbers of the RHS, seeing if any are defined from
2202 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2205 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2208 // DstReg is known to be a register in the RHS interval. If the src is
2209 // from the LHS interval, we can use its value #.
2210 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2213 // Figure out the value # from the LHS.
2214 RHSValsDefinedFromLHS[VNI]=
2215 LHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2218 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2219 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2220 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2222 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2225 unsigned VN = VNI->id;
2226 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2228 ComputeUltimateVN(VNI, NewVNInfo,
2229 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2230 LHSValNoAssignments, RHSValNoAssignments);
2232 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2235 unsigned VN = VNI->id;
2236 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2238 // If this value number isn't a copy from the LHS, it's a new number.
2239 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2240 NewVNInfo.push_back(VNI);
2241 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2245 ComputeUltimateVN(VNI, NewVNInfo,
2246 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2247 RHSValNoAssignments, LHSValNoAssignments);
2251 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2252 // interval lists to see if these intervals are coalescable.
2253 LiveInterval::const_iterator I = LHS.begin();
2254 LiveInterval::const_iterator IE = LHS.end();
2255 LiveInterval::const_iterator J = RHS.begin();
2256 LiveInterval::const_iterator JE = RHS.end();
2258 // Skip ahead until the first place of potential sharing.
2259 if (I->start < J->start) {
2260 I = std::upper_bound(I, IE, J->start);
2261 if (I != LHS.begin()) --I;
2262 } else if (J->start < I->start) {
2263 J = std::upper_bound(J, JE, I->start);
2264 if (J != RHS.begin()) --J;
2268 // Determine if these two live ranges overlap.
2270 if (I->start < J->start) {
2271 Overlaps = I->end > J->start;
2273 Overlaps = J->end > I->start;
2276 // If so, check value # info to determine if they are really different.
2278 // If the live range overlap will map to the same value number in the
2279 // result liverange, we can still coalesce them. If not, we can't.
2280 if (LHSValNoAssignments[I->valno->id] !=
2281 RHSValNoAssignments[J->valno->id])
2285 if (I->end < J->end) {
2294 // Update kill info. Some live ranges are extended due to copy coalescing.
2295 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2296 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2297 VNInfo *VNI = I->first;
2298 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2299 NewVNInfo[LHSValID]->removeKill(VNI->def);
2300 if (VNI->hasPHIKill())
2301 NewVNInfo[LHSValID]->setHasPHIKill(true);
2302 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2305 // Update kill info. Some live ranges are extended due to copy coalescing.
2306 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2307 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2308 VNInfo *VNI = I->first;
2309 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2310 NewVNInfo[RHSValID]->removeKill(VNI->def);
2311 if (VNI->hasPHIKill())
2312 NewVNInfo[RHSValID]->setHasPHIKill(true);
2313 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2316 // If we get here, we know that we can coalesce the live ranges. Ask the
2317 // intervals to coalesce themselves now.
2318 if ((RHS.ranges.size() > LHS.ranges.size() &&
2319 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2320 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2321 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2325 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2333 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2334 // depth of the basic block (the unsigned), and then on the MBB number.
2335 struct DepthMBBCompare {
2336 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2337 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2338 if (LHS.first > RHS.first) return true; // Deeper loops first
2339 return LHS.first == RHS.first &&
2340 LHS.second->getNumber() < RHS.second->getNumber();
2345 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2346 std::vector<CopyRec> &TryAgain) {
2347 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
2349 std::vector<CopyRec> VirtCopies;
2350 std::vector<CopyRec> PhysCopies;
2351 std::vector<CopyRec> ImpDefCopies;
2352 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2354 MachineInstr *Inst = MII++;
2356 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2357 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2358 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2359 DstReg = Inst->getOperand(0).getReg();
2360 SrcReg = Inst->getOperand(1).getReg();
2361 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2362 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
2363 DstReg = Inst->getOperand(0).getReg();
2364 SrcReg = Inst->getOperand(2).getReg();
2365 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2368 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2369 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2370 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2371 ImpDefCopies.push_back(CopyRec(Inst, 0));
2372 else if (SrcIsPhys || DstIsPhys)
2373 PhysCopies.push_back(CopyRec(Inst, 0));
2375 VirtCopies.push_back(CopyRec(Inst, 0));
2378 // Try coalescing implicit copies first, followed by copies to / from
2379 // physical registers, then finally copies from virtual registers to
2380 // virtual registers.
2381 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2382 CopyRec &TheCopy = ImpDefCopies[i];
2384 if (!JoinCopy(TheCopy, Again))
2386 TryAgain.push_back(TheCopy);
2388 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2389 CopyRec &TheCopy = PhysCopies[i];
2391 if (!JoinCopy(TheCopy, Again))
2393 TryAgain.push_back(TheCopy);
2395 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2396 CopyRec &TheCopy = VirtCopies[i];
2398 if (!JoinCopy(TheCopy, Again))
2400 TryAgain.push_back(TheCopy);
2404 void SimpleRegisterCoalescing::joinIntervals() {
2405 DEBUG(errs() << "********** JOINING INTERVALS ***********\n");
2407 std::vector<CopyRec> TryAgainList;
2408 if (loopInfo->empty()) {
2409 // If there are no loops in the function, join intervals in function order.
2410 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2412 CopyCoalesceInMBB(I, TryAgainList);
2414 // Otherwise, join intervals in inner loops before other intervals.
2415 // Unfortunately we can't just iterate over loop hierarchy here because
2416 // there may be more MBB's than BB's. Collect MBB's for sorting.
2418 // Join intervals in the function prolog first. We want to join physical
2419 // registers with virtual registers before the intervals got too long.
2420 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2421 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2422 MachineBasicBlock *MBB = I;
2423 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2426 // Sort by loop depth.
2427 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2429 // Finally, join intervals in loop nest order.
2430 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2431 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2434 // Joining intervals can allow other intervals to be joined. Iteratively join
2435 // until we make no progress.
2436 bool ProgressMade = true;
2437 while (ProgressMade) {
2438 ProgressMade = false;
2440 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2441 CopyRec &TheCopy = TryAgainList[i];
2446 bool Success = JoinCopy(TheCopy, Again);
2447 if (Success || !Again) {
2448 TheCopy.MI = 0; // Mark this one as done.
2449 ProgressMade = true;
2455 /// Return true if the two specified registers belong to different register
2456 /// classes. The registers may be either phys or virt regs.
2458 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2459 unsigned RegB) const {
2460 // Get the register classes for the first reg.
2461 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2462 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2463 "Shouldn't consider two physregs!");
2464 return !mri_->getRegClass(RegB)->contains(RegA);
2467 // Compare against the regclass for the second reg.
2468 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2469 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2470 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2471 return RegClassA != RegClassB;
2473 return !RegClassA->contains(RegB);
2476 /// lastRegisterUse - Returns the last use of the specific register between
2477 /// cycles Start and End or NULL if there are no uses.
2479 SimpleRegisterCoalescing::lastRegisterUse(LiveIndex Start,
2482 LiveIndex &UseIdx) const{
2483 UseIdx = LiveIndex();
2484 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2485 MachineOperand *LastUse = NULL;
2486 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2487 E = mri_->use_end(); I != E; ++I) {
2488 MachineOperand &Use = I.getOperand();
2489 MachineInstr *UseMI = Use.getParent();
2490 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2491 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2493 // Ignore identity copies.
2495 LiveIndex Idx = li_->getInstructionIndex(UseMI);
2496 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2498 UseIdx = li_->getUseIndex(Idx);
2504 LiveIndex s = Start;
2505 LiveIndex e = li_->getBaseIndex(li_->getPrevSlot(End));
2507 // Skip deleted instructions
2508 MachineInstr *MI = li_->getInstructionFromIndex(e);
2509 while (e != LiveIndex() && li_->getPrevIndex(e) >= s && !MI) {
2510 e = li_->getPrevIndex(e);
2511 MI = li_->getInstructionFromIndex(e);
2513 if (e < s || MI == NULL)
2516 // Ignore identity copies.
2517 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2518 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2520 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2521 MachineOperand &Use = MI->getOperand(i);
2522 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2523 tri_->regsOverlap(Use.getReg(), Reg)) {
2524 UseIdx = li_->getUseIndex(e);
2529 e = li_->getPrevIndex(e);
2536 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2537 if (TargetRegisterInfo::isPhysicalRegister(reg))
2538 errs() << tri_->getName(reg);
2540 errs() << "%reg" << reg;
2543 void SimpleRegisterCoalescing::releaseMemory() {
2544 JoinedCopies.clear();
2545 ReMatCopies.clear();
2549 /// Returns true if the given live interval is zero length.
2550 static bool isZeroLengthInterval(LiveInterval *li, LiveIntervals *li_) {
2551 for (LiveInterval::Ranges::const_iterator
2552 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2553 if (li_->getPrevIndex(i->end) > i->start)
2558 void SimpleRegisterCoalescing::CalculateSpillWeights() {
2559 SmallSet<unsigned, 4> Processed;
2560 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2561 mbbi != mbbe; ++mbbi) {
2562 MachineBasicBlock* MBB = mbbi;
2563 LiveIndex MBBEnd = li_->getMBBEndIdx(MBB);
2564 MachineLoop* loop = loopInfo->getLoopFor(MBB);
2565 unsigned loopDepth = loop ? loop->getLoopDepth() : 0;
2566 bool isExit = loop ? loop->isLoopExit(MBB) : false;
2568 for (MachineBasicBlock::iterator mii = MBB->begin(), mie = MBB->end();
2569 mii != mie; ++mii) {
2570 MachineInstr *MI = mii;
2572 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2573 const MachineOperand &mopi = MI->getOperand(i);
2574 if (!mopi.isReg() || mopi.getReg() == 0)
2576 unsigned Reg = mopi.getReg();
2577 if (!TargetRegisterInfo::isVirtualRegister(mopi.getReg()))
2579 // Multiple uses of reg by the same instruction. It should not
2580 // contribute to spill weight again.
2581 if (!Processed.insert(Reg))
2584 bool HasDef = mopi.isDef();
2585 bool HasUse = !HasDef;
2586 for (unsigned j = i+1; j != e; ++j) {
2587 const MachineOperand &mopj = MI->getOperand(j);
2588 if (!mopj.isReg() || mopj.getReg() != Reg)
2590 HasDef |= mopj.isDef();
2591 HasUse |= mopj.isUse();
2592 if (HasDef && HasUse)
2596 LiveInterval &RegInt = li_->getInterval(Reg);
2597 float Weight = li_->getSpillWeight(HasDef, HasUse, loopDepth);
2598 if (HasDef && isExit) {
2599 // Looks like this is a loop count variable update.
2601 li_->getDefIndex(li_->getInstructionIndex(MI));
2602 const LiveRange *DLR =
2603 li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
2604 if (DLR->end > MBBEnd)
2607 RegInt.weight += Weight;
2613 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2614 LiveInterval &LI = *I->second;
2615 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2616 // If the live interval length is essentially zero, i.e. in every live
2617 // range the use follows def immediately, it doesn't make sense to spill
2618 // it and hope it will be easier to allocate for this li.
2619 if (isZeroLengthInterval(&LI, li_)) {
2620 LI.weight = HUGE_VALF;
2624 bool isLoad = false;
2625 SmallVector<LiveInterval*, 4> SpillIs;
2626 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2627 // If all of the definitions of the interval are re-materializable,
2628 // it is a preferred candidate for spilling. If non of the defs are
2629 // loads, then it's potentially very cheap to re-materialize.
2630 // FIXME: this gets much more complicated once we support non-trivial
2631 // re-materialization.
2638 // Slightly prefer live interval that has been assigned a preferred reg.
2639 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2640 if (Hint.first || Hint.second)
2643 // Divide the weight of the interval by its size. This encourages
2644 // spilling of intervals that are large and have few uses, and
2645 // discourages spilling of small intervals with many uses.
2646 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2652 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2654 mri_ = &fn.getRegInfo();
2655 tm_ = &fn.getTarget();
2656 tri_ = tm_->getRegisterInfo();
2657 tii_ = tm_->getInstrInfo();
2658 li_ = &getAnalysis<LiveIntervals>();
2659 loopInfo = &getAnalysis<MachineLoopInfo>();
2661 DEBUG(errs() << "********** SIMPLE REGISTER COALESCING **********\n"
2662 << "********** Function: "
2663 << ((Value*)mf_->getFunction())->getName() << '\n');
2665 allocatableRegs_ = tri_->getAllocatableSet(fn);
2666 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2667 E = tri_->regclass_end(); I != E; ++I)
2668 allocatableRCRegs_.insert(std::make_pair(*I,
2669 tri_->getAllocatableSet(fn, *I)));
2671 // Join (coalesce) intervals if requested.
2672 if (EnableJoining) {
2675 errs() << "********** INTERVALS POST JOINING **********\n";
2676 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2677 I->second->print(errs(), tri_);
2683 // Perform a final pass over the instructions and compute spill weights
2684 // and remove identity moves.
2685 SmallVector<unsigned, 4> DeadDefs;
2686 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2687 mbbi != mbbe; ++mbbi) {
2688 MachineBasicBlock* mbb = mbbi;
2689 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2691 MachineInstr *MI = mii;
2692 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2693 if (JoinedCopies.count(MI)) {
2694 // Delete all coalesced copies.
2695 bool DoDelete = true;
2696 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2697 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2698 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2699 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
2700 "Unrecognized copy instruction");
2701 DstReg = MI->getOperand(0).getReg();
2702 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2703 // Do not delete extract_subreg, insert_subreg of physical
2704 // registers unless the definition is dead. e.g.
2705 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2706 // or else the scavenger may complain. LowerSubregs will
2707 // change this to an IMPLICIT_DEF later.
2710 if (MI->registerDefIsDead(DstReg)) {
2711 LiveInterval &li = li_->getInterval(DstReg);
2712 if (!ShortenDeadCopySrcLiveRange(li, MI))
2713 ShortenDeadCopyLiveRange(li, MI);
2719 li_->RemoveMachineInstrFromMaps(MI);
2720 mii = mbbi->erase(mii);
2726 // Now check if this is a remat'ed def instruction which is now dead.
2727 if (ReMatDefs.count(MI)) {
2729 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2730 const MachineOperand &MO = MI->getOperand(i);
2733 unsigned Reg = MO.getReg();
2736 if (TargetRegisterInfo::isVirtualRegister(Reg))
2737 DeadDefs.push_back(Reg);
2740 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2741 !mri_->use_empty(Reg)) {
2747 while (!DeadDefs.empty()) {
2748 unsigned DeadDef = DeadDefs.back();
2749 DeadDefs.pop_back();
2750 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2752 li_->RemoveMachineInstrFromMaps(mii);
2753 mii = mbbi->erase(mii);
2759 // If the move will be an identity move delete it
2760 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2761 if (isMove && SrcReg == DstReg) {
2762 if (li_->hasInterval(SrcReg)) {
2763 LiveInterval &RegInt = li_->getInterval(SrcReg);
2764 // If def of this move instruction is dead, remove its live range
2765 // from the dstination register's live interval.
2766 if (MI->registerDefIsDead(DstReg)) {
2767 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2768 ShortenDeadCopyLiveRange(RegInt, MI);
2771 li_->RemoveMachineInstrFromMaps(MI);
2772 mii = mbbi->erase(mii);
2780 CalculateSpillWeights();
2786 /// print - Implement the dump method.
2787 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2791 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2792 return new SimpleRegisterCoalescing();
2795 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2796 DEFINING_FILE_FOR(SimpleRegisterCoalescing)