1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
41 STATISTIC(numJoins , "Number of interval joins performed");
42 STATISTIC(numCrossRCs , "Number of cross class joins performed");
43 STATISTIC(numCommutes , "Number of instruction commuting performed");
44 STATISTIC(numExtends , "Number of copies extended");
45 STATISTIC(NumReMats , "Number of instructions re-materialized");
46 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
47 STATISTIC(numAborts , "Number of times interval joining aborted");
48 STATISTIC(numDeadValNo, "Number of valno def marked dead");
50 char SimpleRegisterCoalescing::ID = 0;
52 EnableJoining("join-liveintervals",
53 cl::desc("Coalesce copies (default=true)"),
57 DisableCrossClassJoin("disable-cross-class-join",
58 cl::desc("Avoid coalescing cross register class copies"),
59 cl::init(false), cl::Hidden);
62 PhysJoinTweak("tweak-phys-join-heuristics",
63 cl::desc("Tweak heuristics for joining phys reg with vr"),
64 cl::init(false), cl::Hidden);
66 static RegisterPass<SimpleRegisterCoalescing>
67 X("simple-register-coalescing", "Simple Register Coalescing");
69 // Declare that we implement the RegisterCoalescer interface
70 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
72 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
74 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<AliasAnalysis>();
77 AU.addRequired<LiveIntervals>();
78 AU.addPreserved<LiveIntervals>();
79 AU.addRequired<MachineLoopInfo>();
80 AU.addPreserved<MachineLoopInfo>();
81 AU.addPreservedID(MachineDominatorsID);
83 AU.addPreservedID(StrongPHIEliminationID);
85 AU.addPreservedID(PHIEliminationID);
86 AU.addPreservedID(TwoAddressInstructionPassID);
87 MachineFunctionPass::getAnalysisUsage(AU);
90 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
91 /// being the source and IntB being the dest, thus this defines a value number
92 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
93 /// see if we can merge these two pieces of B into a single value number,
94 /// eliminating a copy. For example:
98 /// B1 = A3 <- this copy
100 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
101 /// value number to be replaced with B0 (which simplifies the B liveinterval).
103 /// This returns true if an interval was modified.
105 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
107 MachineInstr *CopyMI) {
108 LiveIndex CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
110 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
111 // the example above.
112 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
113 assert(BLR != IntB.end() && "Live range not found!");
114 VNInfo *BValNo = BLR->valno;
116 // Get the location that B is defined at. Two options: either this value has
117 // an unknown definition point or it is defined at CopyIdx. If unknown, we
119 if (!BValNo->getCopy()) return false;
120 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
122 // AValNo is the value number in A that defines the copy, A3 in the example.
123 LiveIndex CopyUseIdx = li_->getUseIndex(CopyIdx);
124 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
125 assert(ALR != IntA.end() && "Live range not found!");
126 VNInfo *AValNo = ALR->valno;
127 // If it's re-defined by an early clobber somewhere in the live range, then
128 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
130 // 172 %ECX<def> = MOV32rr %reg1039<kill>
131 // 180 INLINEASM <es:subl $5,$1
132 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
133 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
134 // 188 %EAX<def> = MOV32rr %EAX<kill>
135 // 196 %ECX<def> = MOV32rr %ECX<kill>
136 // 204 %ECX<def> = MOV32rr %ECX<kill>
137 // 212 %EAX<def> = MOV32rr %EAX<kill>
138 // 220 %EAX<def> = MOV32rr %EAX
139 // 228 %reg1039<def> = MOV32rr %ECX<kill>
140 // The early clobber operand ties ECX input to the ECX def.
142 // The live interval of ECX is represented as this:
143 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
144 // The coalescer has no idea there was a def in the middle of [174,230].
145 if (AValNo->hasRedefByEC())
148 // If AValNo is defined as a copy from IntB, we can potentially process this.
149 // Get the instruction that defines this value number.
150 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
151 if (!SrcReg) return false; // Not defined by a copy.
153 // If the value number is not defined by a copy instruction, ignore it.
155 // If the source register comes from an interval other than IntB, we can't
157 if (SrcReg != IntB.reg) return false;
159 // Get the LiveRange in IntB that this value number starts with.
160 LiveInterval::iterator ValLR =
161 IntB.FindLiveRangeContaining(li_->getPrevSlot(AValNo->def));
162 assert(ValLR != IntB.end() && "Live range not found!");
164 // Make sure that the end of the live range is inside the same block as
166 MachineInstr *ValLREndInst =
167 li_->getInstructionFromIndex(li_->getPrevSlot(ValLR->end));
169 ValLREndInst->getParent() != CopyMI->getParent()) return false;
171 // Okay, we now know that ValLR ends in the same block that the CopyMI
172 // live-range starts. If there are no intervening live ranges between them in
173 // IntB, we can merge them.
174 if (ValLR+1 != BLR) return false;
176 // If a live interval is a physical register, conservatively check if any
177 // of its sub-registers is overlapping the live interval of the virtual
178 // register. If so, do not coalesce.
179 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
180 *tri_->getSubRegisters(IntB.reg)) {
181 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
182 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
184 errs() << "Interfere with sub-register ";
185 li_->getInterval(*SR).print(errs(), tri_);
192 errs() << "\nExtending: ";
193 IntB.print(errs(), tri_);
196 LiveIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
197 // We are about to delete CopyMI, so need to remove it as the 'instruction
198 // that defines this value #'. Update the the valnum with the new defining
200 BValNo->def = FillerStart;
203 // Okay, we can merge them. We need to insert a new liverange:
204 // [ValLR.end, BLR.begin) of either value number, then we merge the
205 // two value numbers.
206 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
208 // If the IntB live range is assigned to a physical register, and if that
209 // physreg has sub-registers, update their live intervals as well.
210 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
211 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
212 LiveInterval &SRLI = li_->getInterval(*SR);
213 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
214 SRLI.getNextValue(FillerStart, 0, true,
215 li_->getVNInfoAllocator())));
219 // Okay, merge "B1" into the same value number as "B0".
220 if (BValNo != ValLR->valno) {
221 IntB.addKills(ValLR->valno, BValNo->kills);
222 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
225 errs() << " result = ";
226 IntB.print(errs(), tri_);
230 // If the source instruction was killing the source register before the
231 // merge, unset the isKill marker given the live range has been extended.
232 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
234 ValLREndInst->getOperand(UIdx).setIsKill(false);
235 ValLR->valno->removeKill(FillerStart);
238 // If the copy instruction was killing the destination register before the
239 // merge, find the last use and trim the live range. That will also add the
241 if (CopyMI->killsRegister(IntA.reg))
242 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
248 /// HasOtherReachingDefs - Return true if there are definitions of IntB
249 /// other than BValNo val# that can reach uses of AValno val# of IntA.
250 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
254 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
256 if (AI->valno != AValNo) continue;
257 LiveInterval::Ranges::iterator BI =
258 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
259 if (BI != IntB.ranges.begin())
261 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
262 if (BI->valno == BValNo)
264 if (BI->start <= AI->start && BI->end > AI->start)
266 if (BI->start > AI->start && BI->start < AI->end)
274 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
275 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
277 MachineOperand &MO = MI->getOperand(i);
278 if (MO.isReg() && MO.isImplicit())
279 NewMI->addOperand(MO);
283 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
284 /// being the source and IntB being the dest, thus this defines a value number
285 /// in IntB. If the source value number (in IntA) is defined by a commutable
286 /// instruction and its other operand is coalesced to the copy dest register,
287 /// see if we can transform the copy into a noop by commuting the definition. For
290 /// A3 = op A2 B0<kill>
292 /// B1 = A3 <- this copy
294 /// = op A3 <- more uses
298 /// B2 = op B0 A2<kill>
300 /// B1 = B2 <- now an identify copy
302 /// = op B2 <- more uses
304 /// This returns true if an interval was modified.
306 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
308 MachineInstr *CopyMI) {
310 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
312 // FIXME: For now, only eliminate the copy by commuting its def when the
313 // source register is a virtual register. We want to guard against cases
314 // where the copy is a back edge copy and commuting the def lengthen the
315 // live interval of the source register to the entire loop.
316 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
319 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
320 // the example above.
321 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
322 assert(BLR != IntB.end() && "Live range not found!");
323 VNInfo *BValNo = BLR->valno;
325 // Get the location that B is defined at. Two options: either this value has
326 // an unknown definition point or it is defined at CopyIdx. If unknown, we
328 if (!BValNo->getCopy()) return false;
329 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
331 // AValNo is the value number in A that defines the copy, A3 in the example.
332 LiveInterval::iterator ALR =
333 IntA.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
335 assert(ALR != IntA.end() && "Live range not found!");
336 VNInfo *AValNo = ALR->valno;
337 // If other defs can reach uses of this def, then it's not safe to perform
338 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
340 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
341 AValNo->isUnused() || AValNo->hasPHIKill())
343 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
344 const TargetInstrDesc &TID = DefMI->getDesc();
345 if (!TID.isCommutable())
347 // If DefMI is a two-address instruction then commuting it will change the
348 // destination register.
349 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
350 assert(DefIdx != -1);
352 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
354 unsigned Op1, Op2, NewDstIdx;
355 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
359 else if (Op2 == UseOpIdx)
364 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
365 unsigned NewReg = NewDstMO.getReg();
366 if (NewReg != IntB.reg || !NewDstMO.isKill())
369 // Make sure there are no other definitions of IntB that would reach the
370 // uses which the new definition can reach.
371 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
374 // If some of the uses of IntA.reg is already coalesced away, return false.
375 // It's not possible to determine whether it's safe to perform the coalescing.
376 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
377 UE = mri_->use_end(); UI != UE; ++UI) {
378 MachineInstr *UseMI = &*UI;
379 LiveIndex UseIdx = li_->getInstructionIndex(UseMI);
380 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
381 if (ULR == IntA.end())
383 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
387 // At this point we have decided that it is legal to do this
388 // transformation. Start by commuting the instruction.
389 MachineBasicBlock *MBB = DefMI->getParent();
390 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
393 if (NewMI != DefMI) {
394 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
395 MBB->insert(DefMI, NewMI);
398 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
399 NewMI->getOperand(OpIdx).setIsKill();
401 bool BHasPHIKill = BValNo->hasPHIKill();
402 SmallVector<VNInfo*, 4> BDeadValNos;
403 VNInfo::KillSet BKills;
404 std::map<LiveIndex, LiveIndex> BExtend;
406 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
415 // then do not add kills of A to the newly created B interval.
416 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
418 BExtend[ALR->end] = BLR->end;
420 // Update uses of IntA of the specific Val# with IntB.
421 bool BHasSubRegs = false;
422 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
423 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
424 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
425 UE = mri_->use_end(); UI != UE;) {
426 MachineOperand &UseMO = UI.getOperand();
427 MachineInstr *UseMI = &*UI;
429 if (JoinedCopies.count(UseMI))
431 LiveIndex UseIdx= li_->getUseIndex(li_->getInstructionIndex(UseMI));
432 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
433 if (ULR == IntA.end() || ULR->valno != AValNo)
435 UseMO.setReg(NewReg);
438 if (UseMO.isKill()) {
440 UseMO.setIsKill(false);
442 BKills.push_back(li_->getNextSlot(UseIdx));
444 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
445 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
447 if (DstReg == IntB.reg) {
448 // This copy will become a noop. If it's defining a new val#,
449 // remove that val# as well. However this live range is being
450 // extended to the end of the existing live range defined by the copy.
451 LiveIndex DefIdx = li_->getDefIndex(UseIdx);
452 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
453 BHasPHIKill |= DLR->valno->hasPHIKill();
454 assert(DLR->valno->def == DefIdx);
455 BDeadValNos.push_back(DLR->valno);
456 BExtend[DLR->start] = DLR->end;
457 JoinedCopies.insert(UseMI);
458 // If this is a kill but it's going to be removed, the last use
459 // of the same val# is the new kill.
465 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
466 // simply extend BLR if CopyMI doesn't end the range.
468 errs() << "\nExtending: ";
469 IntB.print(errs(), tri_);
472 // Remove val#'s defined by copies that will be coalesced away.
473 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
474 VNInfo *DeadVNI = BDeadValNos[i];
476 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
477 LiveInterval &SRLI = li_->getInterval(*SR);
478 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
479 SRLI.removeValNo(SRLR->valno);
482 IntB.removeValNo(BDeadValNos[i]);
485 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
486 // is updated. Kills are also updated.
487 VNInfo *ValNo = BValNo;
488 ValNo->def = AValNo->def;
490 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
491 if (ValNo->kills[j] != BLR->end)
492 BKills.push_back(ValNo->kills[j]);
494 ValNo->kills.clear();
495 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
497 if (AI->valno != AValNo) continue;
498 LiveIndex End = AI->end;
499 std::map<LiveIndex, LiveIndex>::iterator
500 EI = BExtend.find(End);
501 if (EI != BExtend.end())
503 IntB.addRange(LiveRange(AI->start, End, ValNo));
505 // If the IntB live range is assigned to a physical register, and if that
506 // physreg has sub-registers, update their live intervals as well.
508 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
509 LiveInterval &SRLI = li_->getInterval(*SR);
510 SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
514 IntB.addKills(ValNo, BKills);
515 ValNo->setHasPHIKill(BHasPHIKill);
518 errs() << " result = ";
519 IntB.print(errs(), tri_);
521 errs() << "\nShortening: ";
522 IntA.print(errs(), tri_);
525 IntA.removeValNo(AValNo);
528 errs() << " result = ";
529 IntA.print(errs(), tri_);
537 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
538 /// fallthoughs to SuccMBB.
539 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
540 MachineBasicBlock *SuccMBB,
541 const TargetInstrInfo *tii_) {
544 MachineBasicBlock *TBB = 0, *FBB = 0;
545 SmallVector<MachineOperand, 4> Cond;
546 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
547 MBB->isSuccessor(SuccMBB);
550 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
551 /// from a physical register live interval as well as from the live intervals
552 /// of its sub-registers.
553 static void removeRange(LiveInterval &li,
554 LiveIndex Start, LiveIndex End,
555 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
556 li.removeRange(Start, End, true);
557 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
558 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
559 if (!li_->hasInterval(*SR))
561 LiveInterval &sli = li_->getInterval(*SR);
562 LiveIndex RemoveStart = Start;
563 LiveIndex RemoveEnd = Start;
564 while (RemoveEnd != End) {
565 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
568 RemoveEnd = (LR->end < End) ? LR->end : End;
569 sli.removeRange(RemoveStart, RemoveEnd, true);
570 RemoveStart = RemoveEnd;
576 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
577 /// as the copy instruction, trim the live interval to the last use and return
580 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(LiveIndex CopyIdx,
581 MachineBasicBlock *CopyMBB,
583 const LiveRange *LR) {
584 LiveIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
585 LiveIndex LastUseIdx;
586 MachineOperand *LastUse =
587 lastRegisterUse(LR->start, li_->getPrevSlot(CopyIdx), li.reg, LastUseIdx);
589 MachineInstr *LastUseMI = LastUse->getParent();
590 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
597 // r1025<dead> = r1024<kill>
598 if (MBBStart < LR->end)
599 removeRange(li, MBBStart, LR->end, li_, tri_);
603 // There are uses before the copy, just shorten the live range to the end
605 LastUse->setIsKill();
606 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
607 LR->valno->addKill(li_->getNextSlot(LastUseIdx));
608 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
609 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
611 // Last use is itself an identity code.
612 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
613 LastUseMI->getOperand(DeadIdx).setIsDead();
619 if (LR->start <= MBBStart && LR->end > MBBStart) {
620 if (LR->start == LiveIndex()) {
621 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
622 // Live-in to the function but dead. Remove it from entry live-in set.
623 mf_->begin()->removeLiveIn(li.reg);
625 // FIXME: Shorten intervals in BBs that reaches this BB.
631 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
632 /// computation, replace the copy by rematerialize the definition.
633 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
636 MachineInstr *CopyMI) {
637 LiveIndex CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
638 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
639 assert(SrcLR != SrcInt.end() && "Live range not found!");
640 VNInfo *ValNo = SrcLR->valno;
641 // If other defs can reach uses of this def, then it's not safe to perform
642 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
644 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
645 ValNo->isUnused() || ValNo->hasPHIKill())
647 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
648 const TargetInstrDesc &TID = DefMI->getDesc();
649 if (!TID.isAsCheapAsAMove())
651 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
653 bool SawStore = false;
654 if (!DefMI->isSafeToMove(tii_, SawStore, AA))
656 if (TID.getNumDefs() != 1)
658 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
659 // Make sure the copy destination register class fits the instruction
660 // definition register class. The mismatch can happen as a result of earlier
661 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
662 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
663 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
664 if (mri_->getRegClass(DstReg) != RC)
666 } else if (!RC->contains(DstReg))
670 // If destination register has a sub-register index on it, make sure it mtches
671 // the instruction register class.
673 const TargetInstrDesc &TID = DefMI->getDesc();
674 if (TID.getNumDefs() != 1)
676 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
677 const TargetRegisterClass *DstSubRC =
678 DstRC->getSubRegisterRegClass(DstSubIdx);
679 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
682 else if (DefRC != DstSubRC)
686 LiveIndex DefIdx = li_->getDefIndex(CopyIdx);
687 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
688 DLR->valno->setCopy(0);
689 // Don't forget to update sub-register intervals.
690 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
691 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
692 if (!li_->hasInterval(*SR))
694 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
695 if (DLR && DLR->valno->getCopy() == CopyMI)
696 DLR->valno->setCopy(0);
700 // If copy kills the source register, find the last use and propagate
702 bool checkForDeadDef = false;
703 MachineBasicBlock *MBB = CopyMI->getParent();
704 if (CopyMI->killsRegister(SrcInt.reg))
705 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
706 checkForDeadDef = true;
709 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
710 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI);
711 MachineInstr *NewMI = prior(MII);
713 if (checkForDeadDef) {
714 // PR4090 fix: Trim interval failed because there was no use of the
715 // source interval in this MBB. If the def is in this MBB too then we
716 // should mark it dead:
717 if (DefMI->getParent() == MBB) {
718 DefMI->addRegisterDead(SrcInt.reg, tri_);
719 SrcLR->end = li_->getNextSlot(SrcLR->start);
723 // CopyMI may have implicit operands, transfer them over to the newly
724 // rematerialized instruction. And update implicit def interval valnos.
725 for (unsigned i = CopyMI->getDesc().getNumOperands(),
726 e = CopyMI->getNumOperands(); i != e; ++i) {
727 MachineOperand &MO = CopyMI->getOperand(i);
728 if (MO.isReg() && MO.isImplicit())
729 NewMI->addOperand(MO);
730 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
731 unsigned Reg = MO.getReg();
732 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
733 if (DLR && DLR->valno->getCopy() == CopyMI)
734 DLR->valno->setCopy(0);
738 TransferImplicitOps(CopyMI, NewMI);
739 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
740 CopyMI->eraseFromParent();
741 ReMatCopies.insert(CopyMI);
742 ReMatDefs.insert(DefMI);
747 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
748 /// update the subregister number if it is not zero. If DstReg is a
749 /// physical register and the existing subregister number of the def / use
750 /// being updated is not zero, make sure to set it to the correct physical
753 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
755 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
756 if (DstIsPhys && SubIdx) {
757 // Figure out the real physical register we are updating with.
758 DstReg = tri_->getSubReg(DstReg, SubIdx);
762 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
763 E = mri_->reg_end(); I != E; ) {
764 MachineOperand &O = I.getOperand();
765 MachineInstr *UseMI = &*I;
767 unsigned OldSubIdx = O.getSubReg();
769 unsigned UseDstReg = DstReg;
771 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
773 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
774 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
775 CopySrcSubIdx, CopyDstSubIdx) &&
776 CopySrcReg != CopyDstReg &&
777 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
778 // If the use is a copy and it won't be coalesced away, and its source
779 // is defined by a trivial computation, try to rematerialize it instead.
780 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
781 CopyDstSubIdx, UseMI))
790 // Sub-register indexes goes from small to large. e.g.
791 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
792 // EAX: 1 -> AL, 2 -> AX
793 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
794 // sub-register 2 is also AX.
795 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
796 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
799 // Remove would-be duplicated kill marker.
800 if (O.isKill() && UseMI->killsRegister(DstReg))
804 // After updating the operand, check if the machine instruction has
805 // become a copy. If so, update its val# information.
806 if (JoinedCopies.count(UseMI))
809 const TargetInstrDesc &TID = UseMI->getDesc();
810 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
811 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
812 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
813 CopySrcSubIdx, CopyDstSubIdx) &&
814 CopySrcReg != CopyDstReg &&
815 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
816 allocatableRegs_[CopyDstReg])) {
817 LiveInterval &LI = li_->getInterval(CopyDstReg);
819 li_->getDefIndex(li_->getInstructionIndex(UseMI));
820 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
821 if (DLR->valno->def == DefIdx)
822 DLR->valno->setCopy(UseMI);
828 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
829 /// due to live range lengthening as the result of coalescing.
830 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
832 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
833 UE = mri_->use_end(); UI != UE; ++UI) {
834 MachineOperand &UseMO = UI.getOperand();
837 MachineInstr *UseMI = UseMO.getParent();
839 li_->getUseIndex(li_->getInstructionIndex(UseMI));
840 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
842 (!LR->valno->isKill(li_->getNextSlot(UseIdx)) &&
843 LR->valno->def != li_->getNextSlot(UseIdx))) {
844 // Interesting problem. After coalescing reg1027's def and kill are both
845 // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814)
848 // 60 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
849 // 68 %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
850 // 76 t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
851 // 84 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
852 // 96 t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
854 // Do not remove the kill marker on t2LDRi12.
855 UseMO.setIsKill(false);
860 /// removeIntervalIfEmpty - Check if the live interval of a physical register
861 /// is empty, if so remove it and also remove the empty intervals of its
862 /// sub-registers. Return true if live interval is removed.
863 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
864 const TargetRegisterInfo *tri_) {
866 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
867 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
868 if (!li_->hasInterval(*SR))
870 LiveInterval &sli = li_->getInterval(*SR);
872 li_->removeInterval(*SR);
874 li_->removeInterval(li.reg);
880 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
881 /// Return true if live interval is removed.
882 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
883 MachineInstr *CopyMI) {
884 LiveIndex CopyIdx = li_->getInstructionIndex(CopyMI);
885 LiveInterval::iterator MLR =
886 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
888 return false; // Already removed by ShortenDeadCopySrcLiveRange.
889 LiveIndex RemoveStart = MLR->start;
890 LiveIndex RemoveEnd = MLR->end;
891 LiveIndex DefIdx = li_->getDefIndex(CopyIdx);
892 // Remove the liverange that's defined by this.
893 if (RemoveStart == DefIdx && RemoveEnd == li_->getNextSlot(DefIdx)) {
894 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
895 return removeIntervalIfEmpty(li, li_, tri_);
900 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
901 /// the val# it defines. If the live interval becomes empty, remove it as well.
902 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
903 MachineInstr *DefMI) {
904 LiveIndex DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
905 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
906 if (DefIdx != MLR->valno->def)
908 li.removeValNo(MLR->valno);
909 return removeIntervalIfEmpty(li, li_, tri_);
912 /// PropagateDeadness - Propagate the dead marker to the instruction which
913 /// defines the val#.
914 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
915 LiveIndex &LRStart, LiveIntervals *li_,
916 const TargetRegisterInfo* tri_) {
917 MachineInstr *DefMI =
918 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
919 if (DefMI && DefMI != CopyMI) {
920 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
922 DefMI->getOperand(DeadIdx).setIsDead();
924 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
925 true, true, false, true));
926 LRStart = li_->getNextSlot(LRStart);
930 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
931 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
932 /// ends the live range there. If there isn't another use, then this live range
933 /// is dead. Return true if live interval is removed.
935 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
936 MachineInstr *CopyMI) {
937 LiveIndex CopyIdx = li_->getInstructionIndex(CopyMI);
938 if (CopyIdx == LiveIndex()) {
939 // FIXME: special case: function live in. It can be a general case if the
940 // first instruction index starts at > 0 value.
941 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
942 // Live-in to the function but dead. Remove it from entry live-in set.
943 if (mf_->begin()->isLiveIn(li.reg))
944 mf_->begin()->removeLiveIn(li.reg);
945 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
946 removeRange(li, LR->start, LR->end, li_, tri_);
947 return removeIntervalIfEmpty(li, li_, tri_);
950 LiveInterval::iterator LR =
951 li.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
953 // Livein but defined by a phi.
956 LiveIndex RemoveStart = LR->start;
957 LiveIndex RemoveEnd = li_->getNextSlot(li_->getDefIndex(CopyIdx));
958 if (LR->end > RemoveEnd)
959 // More uses past this copy? Nothing to do.
962 // If there is a last use in the same bb, we can't remove the live range.
963 // Shorten the live interval and return.
964 MachineBasicBlock *CopyMBB = CopyMI->getParent();
965 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
968 // There are other kills of the val#. Nothing to do.
969 if (!li.isOnlyLROfValNo(LR))
972 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
973 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
974 // If the live range starts in another mbb and the copy mbb is not a fall
975 // through mbb, then we can only cut the range from the beginning of the
977 RemoveStart = li_->getNextSlot(li_->getMBBStartIdx(CopyMBB));
979 if (LR->valno->def == RemoveStart) {
980 // If the def MI defines the val# and this copy is the only kill of the
981 // val#, then propagate the dead marker.
982 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
985 if (LR->valno->isKill(RemoveEnd))
986 LR->valno->removeKill(RemoveEnd);
989 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
990 return removeIntervalIfEmpty(li, li_, tri_);
993 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
994 /// from an implicit def to another register can be coalesced away.
995 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
997 LiveInterval &ImpLi) const{
998 if (!CopyMI->killsRegister(ImpLi.reg))
1000 // Make sure this is the only use.
1001 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1002 UE = mri_->use_end(); UI != UE;) {
1003 MachineInstr *UseMI = &*UI;
1005 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1013 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1014 /// a virtual destination register with physical source register.
1016 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1017 MachineBasicBlock *CopyMBB,
1018 LiveInterval &DstInt,
1019 LiveInterval &SrcInt) {
1020 // If the virtual register live interval is long but it has low use desity,
1021 // do not join them, instead mark the physical register as its allocation
1023 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1024 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1025 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1026 if (Length > Threshold &&
1027 (((float)std::distance(mri_->use_begin(DstInt.reg),
1028 mri_->use_end()) / Length) < (1.0 / Threshold)))
1031 // If the virtual register live interval extends into a loop, turn down
1034 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1035 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1037 // Let's see if the virtual register live interval extends into the loop.
1038 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1039 assert(DLR != DstInt.end() && "Live range not found!");
1040 DLR = DstInt.FindLiveRangeContaining(li_->getNextSlot(DLR->end));
1041 if (DLR != DstInt.end()) {
1042 CopyMBB = li_->getMBBFromIndex(DLR->start);
1043 L = loopInfo->getLoopFor(CopyMBB);
1047 if (!L || Length <= Threshold)
1050 LiveIndex UseIdx = li_->getUseIndex(CopyIdx);
1051 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1052 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1053 if (loopInfo->getLoopFor(SMBB) != L) {
1054 if (!loopInfo->isLoopHeader(CopyMBB))
1056 // If vr's live interval extends pass the loop header, do not join.
1057 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1058 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1059 MachineBasicBlock *SuccMBB = *SI;
1060 if (SuccMBB == CopyMBB)
1062 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1063 li_->getNextSlot(li_->getMBBEndIdx(SuccMBB))))
1070 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1071 /// copy from a virtual source register to a physical destination register.
1073 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1074 MachineBasicBlock *CopyMBB,
1075 LiveInterval &DstInt,
1076 LiveInterval &SrcInt) {
1077 // If the virtual register live interval is long but it has low use desity,
1078 // do not join them, instead mark the physical register as its allocation
1080 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1081 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1082 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1083 if (Length > Threshold &&
1084 (((float)std::distance(mri_->use_begin(SrcInt.reg),
1085 mri_->use_end()) / Length) < (1.0 / Threshold)))
1089 // Must be implicit_def.
1092 // If the virtual register live interval is defined or cross a loop, turn
1093 // down aggressiveness.
1095 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1096 LiveIndex UseIdx = li_->getUseIndex(CopyIdx);
1097 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1098 assert(SLR != SrcInt.end() && "Live range not found!");
1099 SLR = SrcInt.FindLiveRangeContaining(li_->getPrevSlot(SLR->start));
1100 if (SLR == SrcInt.end())
1102 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1103 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1105 if (!L || Length <= Threshold)
1108 if (loopInfo->getLoopFor(CopyMBB) != L) {
1109 if (SMBB != L->getLoopLatch())
1111 // If vr's live interval is extended from before the loop latch, do not
1113 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1114 PE = SMBB->pred_end(); PI != PE; ++PI) {
1115 MachineBasicBlock *PredMBB = *PI;
1116 if (PredMBB == SMBB)
1118 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1119 li_->getNextSlot(li_->getMBBEndIdx(PredMBB))))
1126 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1127 /// two virtual registers from different register classes.
1129 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1131 unsigned Threshold) {
1132 // Then make sure the intervals are *short*.
1133 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1134 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1135 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1136 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1137 if (SmallSize > Threshold || LargeSize > Threshold)
1138 if ((float)std::distance(mri_->use_begin(SmallReg),
1139 mri_->use_end()) / SmallSize <
1140 (float)std::distance(mri_->use_begin(LargeReg),
1141 mri_->use_end()) / LargeSize)
1146 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1147 /// register with a physical register, check if any of the virtual register
1148 /// operand is a sub-register use or def. If so, make sure it won't result
1149 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1150 /// vr1024 = extract_subreg vr1025, 1
1152 /// vr1024 = mov8rr AH
1153 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1154 /// AH does not have a super-reg whose sub-register 1 is AH.
1156 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1159 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1160 E = mri_->reg_end(); I != E; ++I) {
1161 MachineOperand &O = I.getOperand();
1162 MachineInstr *MI = &*I;
1163 if (MI == CopyMI || JoinedCopies.count(MI))
1165 unsigned SubIdx = O.getSubReg();
1166 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1168 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1169 SubIdx = MI->getOperand(2).getImm();
1170 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1173 unsigned SrcReg = MI->getOperand(1).getReg();
1174 const TargetRegisterClass *RC =
1175 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1176 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1177 : mri_->getRegClass(SrcReg);
1178 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1182 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1183 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
1184 SubIdx = MI->getOperand(3).getImm();
1185 if (VirtReg == MI->getOperand(0).getReg()) {
1186 if (!tri_->getSubReg(PhysReg, SubIdx))
1189 unsigned DstReg = MI->getOperand(0).getReg();
1190 const TargetRegisterClass *RC =
1191 TargetRegisterInfo::isPhysicalRegister(DstReg)
1192 ? tri_->getPhysicalRegisterRegClass(DstReg)
1193 : mri_->getRegClass(DstReg);
1194 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1203 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1204 /// an extract_subreg where dst is a physical register, e.g.
1205 /// cl = EXTRACT_SUBREG reg1024, 1
1207 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1208 unsigned SrcReg, unsigned SubIdx,
1209 unsigned &RealDstReg) {
1210 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1211 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1212 assert(RealDstReg && "Invalid extract_subreg instruction!");
1214 // For this type of EXTRACT_SUBREG, conservatively
1215 // check if the live interval of the source register interfere with the
1216 // actual super physical register we are trying to coalesce with.
1217 LiveInterval &RHS = li_->getInterval(SrcReg);
1218 if (li_->hasInterval(RealDstReg) &&
1219 RHS.overlaps(li_->getInterval(RealDstReg))) {
1221 errs() << "Interfere with register ";
1222 li_->getInterval(RealDstReg).print(errs(), tri_);
1224 return false; // Not coalescable
1226 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1227 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1229 errs() << "Interfere with sub-register ";
1230 li_->getInterval(*SR).print(errs(), tri_);
1232 return false; // Not coalescable
1237 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1238 /// an insert_subreg where src is a physical register, e.g.
1239 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1241 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1242 unsigned SrcReg, unsigned SubIdx,
1243 unsigned &RealSrcReg) {
1244 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1245 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1246 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1248 LiveInterval &RHS = li_->getInterval(DstReg);
1249 if (li_->hasInterval(RealSrcReg) &&
1250 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1252 errs() << "Interfere with register ";
1253 li_->getInterval(RealSrcReg).print(errs(), tri_);
1255 return false; // Not coalescable
1257 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1258 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1260 errs() << "Interfere with sub-register ";
1261 li_->getInterval(*SR).print(errs(), tri_);
1263 return false; // Not coalescable
1268 /// getRegAllocPreference - Return register allocation preference register.
1270 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1271 MachineRegisterInfo *MRI,
1272 const TargetRegisterInfo *TRI) {
1273 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1275 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1276 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1279 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1280 /// which are the src/dst of the copy instruction CopyMI. This returns true
1281 /// if the copy was successfully coalesced away. If it is not currently
1282 /// possible to coalesce this interval, but it may be possible if other
1283 /// things get coalesced, then it returns true by reference in 'Again'.
1284 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1285 MachineInstr *CopyMI = TheCopy.MI;
1288 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1289 return false; // Already done.
1291 DEBUG(errs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1293 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1294 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1295 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1296 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
1297 unsigned SubIdx = 0;
1299 DstReg = CopyMI->getOperand(0).getReg();
1300 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1301 SrcReg = CopyMI->getOperand(1).getReg();
1302 SrcSubIdx = CopyMI->getOperand(2).getImm();
1303 } else if (isInsSubReg || isSubRegToReg) {
1304 DstReg = CopyMI->getOperand(0).getReg();
1305 DstSubIdx = CopyMI->getOperand(3).getImm();
1306 SrcReg = CopyMI->getOperand(2).getReg();
1307 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1308 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1309 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1310 // coalesced to a larger register so the subreg indices cancel out.
1311 DEBUG(errs() << "\tSource of insert_subreg or subreg_to_reg is already "
1312 "coalesced to another register.\n");
1313 return false; // Not coalescable.
1315 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1316 llvm_unreachable("Unrecognized copy instruction!");
1319 // If they are already joined we continue.
1320 if (SrcReg == DstReg) {
1321 DEBUG(errs() << "\tCopy already coalesced.\n");
1322 return false; // Not coalescable.
1325 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1326 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1328 // If they are both physical registers, we cannot join them.
1329 if (SrcIsPhys && DstIsPhys) {
1330 DEBUG(errs() << "\tCan not coalesce physregs.\n");
1331 return false; // Not coalescable.
1334 // We only join virtual registers with allocatable physical registers.
1335 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1336 DEBUG(errs() << "\tSrc reg is unallocatable physreg.\n");
1337 return false; // Not coalescable.
1339 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1340 DEBUG(errs() << "\tDst reg is unallocatable physreg.\n");
1341 return false; // Not coalescable.
1344 // Check that a physical source register is compatible with dst regclass
1346 unsigned SrcSubReg = SrcSubIdx ?
1347 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1348 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1349 const TargetRegisterClass *DstSubRC = DstRC;
1351 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1352 assert(DstSubRC && "Illegal subregister index");
1353 if (!DstSubRC->contains(SrcSubReg)) {
1354 DEBUG(errs() << "\tIncompatible destination regclass: "
1355 << tri_->getName(SrcSubReg) << " not in "
1356 << DstSubRC->getName() << ".\n");
1357 return false; // Not coalescable.
1361 // Check that a physical dst register is compatible with source regclass
1363 unsigned DstSubReg = DstSubIdx ?
1364 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1365 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1366 const TargetRegisterClass *SrcSubRC = SrcRC;
1368 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1369 assert(SrcSubRC && "Illegal subregister index");
1370 if (!SrcSubRC->contains(DstReg)) {
1371 DEBUG(errs() << "\tIncompatible source regclass: "
1372 << tri_->getName(DstSubReg) << " not in "
1373 << SrcSubRC->getName() << ".\n");
1375 return false; // Not coalescable.
1379 // Should be non-null only when coalescing to a sub-register class.
1380 bool CrossRC = false;
1381 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1382 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1383 const TargetRegisterClass *NewRC = NULL;
1384 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1385 unsigned RealDstReg = 0;
1386 unsigned RealSrcReg = 0;
1387 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1388 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1389 if (SrcIsPhys && isExtSubReg) {
1390 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1391 // coalesced with AX.
1392 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1394 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1395 // coalesced to a larger register so the subreg indices cancel out.
1396 if (DstSubIdx != SubIdx) {
1397 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1398 return false; // Not coalescable.
1401 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1403 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1404 // EAX = INSERT_SUBREG EAX, r1024, 0
1405 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1407 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1408 // coalesced to a larger register so the subreg indices cancel out.
1409 if (SrcSubIdx != SubIdx) {
1410 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1411 return false; // Not coalescable.
1414 DstReg = tri_->getSubReg(DstReg, SubIdx);
1416 } else if ((DstIsPhys && isExtSubReg) ||
1417 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1418 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1419 DEBUG(errs() << "\tSrc of extract_subreg already coalesced with reg"
1420 << " of a super-class.\n");
1421 return false; // Not coalescable.
1425 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1426 return false; // Not coalescable
1428 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1429 return false; // Not coalescable
1433 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1434 : CopyMI->getOperand(2).getSubReg();
1436 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1437 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1438 // coalesced to a larger register so the subreg indices cancel out.
1439 // Also check if the other larger register is of the same register
1440 // class as the would be resulting register.
1443 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1444 return false; // Not coalescable.
1448 if (!DstIsPhys && !SrcIsPhys) {
1449 if (isInsSubReg || isSubRegToReg) {
1450 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1451 } else // extract_subreg {
1452 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1455 DEBUG(errs() << "\t Conflicting sub-register indices.\n");
1456 return false; // Not coalescable
1459 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1460 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1461 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1462 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1463 Again = true; // May be possible to coalesce later.
1468 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1469 if (DisableCrossClassJoin)
1473 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1474 // with another? If it's the resulting destination register, then
1475 // the subidx must be propagated to uses (but only those defined
1476 // by the EXTRACT_SUBREG). If it's being coalesced into another
1477 // register, it should be safe because register is assumed to have
1478 // the register class of the super-register.
1480 // Process moves where one of the registers have a sub-register index.
1481 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1482 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1483 SubIdx = DstMO->getSubReg();
1485 if (SrcMO->getSubReg())
1486 // FIXME: can we handle this?
1488 // This is not an insert_subreg but it looks like one.
1489 // e.g. %reg1024:4 = MOV32rr %EAX
1492 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1493 return false; // Not coalescable
1497 SubIdx = SrcMO->getSubReg();
1499 // This is not a extract_subreg but it looks like one.
1500 // e.g. %cl = MOV16rr %reg1024:1
1503 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1504 return false; // Not coalescable
1510 unsigned LargeReg = SrcReg;
1511 unsigned SmallReg = DstReg;
1513 // Now determine the register class of the joined register.
1515 if (SubIdx && DstRC && DstRC->isASubClass()) {
1516 // This is a move to a sub-register class. However, the source is a
1517 // sub-register of a larger register class. We don't know what should
1518 // the register class be. FIXME.
1522 if (!DstIsPhys && !SrcIsPhys)
1524 } else if (!SrcIsPhys && !DstIsPhys) {
1525 NewRC = getCommonSubClass(SrcRC, DstRC);
1527 DEBUG(errs() << "\tDisjoint regclasses: "
1528 << SrcRC->getName() << ", "
1529 << DstRC->getName() << ".\n");
1530 return false; // Not coalescable.
1532 if (DstRC->getSize() > SrcRC->getSize())
1533 std::swap(LargeReg, SmallReg);
1536 // If we are joining two virtual registers and the resulting register
1537 // class is more restrictive (fewer register, smaller size). Check if it's
1538 // worth doing the merge.
1539 if (!SrcIsPhys && !DstIsPhys &&
1540 (isExtSubReg || DstRC->isASubClass()) &&
1541 !isWinToJoinCrossClass(LargeReg, SmallReg,
1542 allocatableRCRegs_[NewRC].count())) {
1543 DEBUG(errs() << "\tSrc/Dest are different register classes.\n");
1544 // Allow the coalescer to try again in case either side gets coalesced to
1545 // a physical register that's compatible with the other side. e.g.
1546 // r1024 = MOV32to32_ r1025
1547 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1548 Again = true; // May be possible to coalesce later.
1553 // Will it create illegal extract_subreg / insert_subreg?
1554 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1556 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1559 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1560 LiveInterval &DstInt = li_->getInterval(DstReg);
1561 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1562 "Register mapping is horribly broken!");
1565 errs() << "\t\tInspecting "; SrcInt.print(errs(), tri_);
1566 errs() << " and "; DstInt.print(errs(), tri_);
1570 // Save a copy of the virtual register live interval. We'll manually
1571 // merge this into the "real" physical register live interval this is
1573 LiveInterval *SavedLI = 0;
1575 SavedLI = li_->dupInterval(&SrcInt);
1576 else if (RealSrcReg)
1577 SavedLI = li_->dupInterval(&DstInt);
1579 // Check if it is necessary to propagate "isDead" property.
1580 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1581 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1582 bool isDead = mopd->isDead();
1584 // We need to be careful about coalescing a source physical register with a
1585 // virtual register. Once the coalescing is done, it cannot be broken and
1586 // these are not spillable! If the destination interval uses are far away,
1587 // think twice about coalescing them!
1588 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1589 // If the copy is in a loop, take care not to coalesce aggressively if the
1590 // src is coming in from outside the loop (or the dst is out of the loop).
1591 // If it's not in a loop, then determine whether to join them base purely
1592 // by the length of the interval.
1593 if (PhysJoinTweak) {
1595 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1596 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1598 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1599 Again = true; // May be possible to coalesce later.
1603 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1604 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1606 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1607 Again = true; // May be possible to coalesce later.
1612 // If the virtual register live interval is long but it has low use desity,
1613 // do not join them, instead mark the physical register as its allocation
1615 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1616 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1617 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1618 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1619 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1620 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1621 float Ratio = 1.0 / Threshold;
1622 if (Length > Threshold &&
1623 (((float)std::distance(mri_->use_begin(JoinVReg),
1624 mri_->use_end()) / Length) < Ratio)) {
1625 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1627 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1628 Again = true; // May be possible to coalesce later.
1635 // Okay, attempt to join these two intervals. On failure, this returns false.
1636 // Otherwise, if one of the intervals being joined is a physreg, this method
1637 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1638 // been modified, so we can use this information below to update aliases.
1639 bool Swapped = false;
1640 // If SrcInt is implicitly defined, it's safe to coalesce.
1641 bool isEmpty = SrcInt.empty();
1642 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1643 // Only coalesce an empty interval (defined by implicit_def) with
1644 // another interval which has a valno defined by the CopyMI and the CopyMI
1645 // is a kill of the implicit def.
1646 DEBUG(errs() << "Not profitable!\n");
1650 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1651 // Coalescing failed.
1653 // If definition of source is defined by trivial computation, try
1654 // rematerializing it.
1655 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1656 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1659 // If we can eliminate the copy without merging the live ranges, do so now.
1660 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1661 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1662 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1663 JoinedCopies.insert(CopyMI);
1667 // Otherwise, we are unable to join the intervals.
1668 DEBUG(errs() << "Interference!\n");
1669 Again = true; // May be possible to coalesce later.
1673 LiveInterval *ResSrcInt = &SrcInt;
1674 LiveInterval *ResDstInt = &DstInt;
1676 std::swap(SrcReg, DstReg);
1677 std::swap(ResSrcInt, ResDstInt);
1679 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1680 "LiveInterval::join didn't work right!");
1682 // If we're about to merge live ranges into a physical register live interval,
1683 // we have to update any aliased register's live ranges to indicate that they
1684 // have clobbered values for this range.
1685 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1686 // If this is a extract_subreg where dst is a physical register, e.g.
1687 // cl = EXTRACT_SUBREG reg1024, 1
1688 // then create and update the actual physical register allocated to RHS.
1689 if (RealDstReg || RealSrcReg) {
1690 LiveInterval &RealInt =
1691 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1692 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1693 E = SavedLI->vni_end(); I != E; ++I) {
1694 const VNInfo *ValNo = *I;
1695 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1696 false, // updated at *
1697 li_->getVNInfoAllocator());
1698 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1699 RealInt.addKills(NewValNo, ValNo->kills);
1700 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1702 RealInt.weight += SavedLI->weight;
1703 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1706 // Update the liveintervals of sub-registers.
1707 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1708 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1709 li_->getVNInfoAllocator());
1712 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1713 // larger super-register.
1714 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1715 !SrcIsPhys && !DstIsPhys) {
1716 if ((isExtSubReg && !Swapped) ||
1717 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1718 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1719 std::swap(SrcReg, DstReg);
1720 std::swap(ResSrcInt, ResDstInt);
1724 // Coalescing to a virtual register that is of a sub-register class of the
1725 // other. Make sure the resulting register is set to the right register class.
1729 // This may happen even if it's cross-rc coalescing. e.g.
1730 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1731 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1732 // be allocate a register from GR64_ABCD.
1734 mri_->setRegClass(DstReg, NewRC);
1736 // Remember to delete the copy instruction.
1737 JoinedCopies.insert(CopyMI);
1739 // Some live range has been lengthened due to colaescing, eliminate the
1740 // unnecessary kills.
1741 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1742 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1743 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1745 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1747 // SrcReg is guarateed to be the register whose live interval that is
1749 li_->removeInterval(SrcReg);
1751 // Update regalloc hint.
1752 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1754 // Manually deleted the live interval copy.
1760 // If resulting interval has a preference that no longer fits because of subreg
1761 // coalescing, just clear the preference.
1762 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1763 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1764 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1765 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1766 if (!RC->contains(Preference))
1767 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1771 errs() << "\n\t\tJoined. Result = ";
1772 ResDstInt->print(errs(), tri_);
1780 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1781 /// compute what the resultant value numbers for each value in the input two
1782 /// ranges will be. This is complicated by copies between the two which can
1783 /// and will commonly cause multiple value numbers to be merged into one.
1785 /// VN is the value number that we're trying to resolve. InstDefiningValue
1786 /// keeps track of the new InstDefiningValue assignment for the result
1787 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1788 /// whether a value in this or other is a copy from the opposite set.
1789 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1790 /// already been assigned.
1792 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1793 /// contains the value number the copy is from.
1795 static unsigned ComputeUltimateVN(VNInfo *VNI,
1796 SmallVector<VNInfo*, 16> &NewVNInfo,
1797 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1798 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1799 SmallVector<int, 16> &ThisValNoAssignments,
1800 SmallVector<int, 16> &OtherValNoAssignments) {
1801 unsigned VN = VNI->id;
1803 // If the VN has already been computed, just return it.
1804 if (ThisValNoAssignments[VN] >= 0)
1805 return ThisValNoAssignments[VN];
1806 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1808 // If this val is not a copy from the other val, then it must be a new value
1809 // number in the destination.
1810 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1811 if (I == ThisFromOther.end()) {
1812 NewVNInfo.push_back(VNI);
1813 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1815 VNInfo *OtherValNo = I->second;
1817 // Otherwise, this *is* a copy from the RHS. If the other side has already
1818 // been computed, return it.
1819 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1820 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1822 // Mark this value number as currently being computed, then ask what the
1823 // ultimate value # of the other value is.
1824 ThisValNoAssignments[VN] = -2;
1825 unsigned UltimateVN =
1826 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1827 OtherValNoAssignments, ThisValNoAssignments);
1828 return ThisValNoAssignments[VN] = UltimateVN;
1831 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1832 return std::find(V.begin(), V.end(), Val) != V.end();
1835 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1836 /// the specified live interval is defined by a copy from the specified
1838 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1841 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1844 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1845 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1846 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1847 *tri_->getSuperRegisters(li.reg)) {
1848 // It's a sub-register live interval, we may not have precise information.
1850 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1851 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1853 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1854 DstReg == li.reg && SrcReg == Reg) {
1855 // Cache computed info.
1856 LR->valno->def = LR->start;
1857 LR->valno->setCopy(DefMI);
1864 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1865 /// caller of this method must guarantee that the RHS only contains a single
1866 /// value number and that the RHS is not defined by a copy from this
1867 /// interval. This returns false if the intervals are not joinable, or it
1868 /// joins them and returns true.
1869 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1870 assert(RHS.containsOneValue());
1872 // Some number (potentially more than one) value numbers in the current
1873 // interval may be defined as copies from the RHS. Scan the overlapping
1874 // portions of the LHS and RHS, keeping track of this and looking for
1875 // overlapping live ranges that are NOT defined as copies. If these exist, we
1878 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1879 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1881 if (LHSIt->start < RHSIt->start) {
1882 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1883 if (LHSIt != LHS.begin()) --LHSIt;
1884 } else if (RHSIt->start < LHSIt->start) {
1885 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1886 if (RHSIt != RHS.begin()) --RHSIt;
1889 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1892 // Determine if these live intervals overlap.
1893 bool Overlaps = false;
1894 if (LHSIt->start <= RHSIt->start)
1895 Overlaps = LHSIt->end > RHSIt->start;
1897 Overlaps = RHSIt->end > LHSIt->start;
1899 // If the live intervals overlap, there are two interesting cases: if the
1900 // LHS interval is defined by a copy from the RHS, it's ok and we record
1901 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1902 // coalesce these live ranges and we bail out.
1904 // If we haven't already recorded that this value # is safe, check it.
1905 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1906 // Copy from the RHS?
1907 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1908 return false; // Nope, bail out.
1910 if (LHSIt->contains(RHSIt->valno->def))
1911 // Here is an interesting situation:
1913 // vr1025 = copy vr1024
1918 // Even though vr1025 is copied from vr1024, it's not safe to
1919 // coalesce them since the live range of vr1025 intersects the
1920 // def of vr1024. This happens because vr1025 is assigned the
1921 // value of the previous iteration of vr1024.
1923 EliminatedLHSVals.push_back(LHSIt->valno);
1926 // We know this entire LHS live range is okay, so skip it now.
1927 if (++LHSIt == LHSEnd) break;
1931 if (LHSIt->end < RHSIt->end) {
1932 if (++LHSIt == LHSEnd) break;
1934 // One interesting case to check here. It's possible that we have
1935 // something like "X3 = Y" which defines a new value number in the LHS,
1936 // and is the last use of this liverange of the RHS. In this case, we
1937 // want to notice this copy (so that it gets coalesced away) even though
1938 // the live ranges don't actually overlap.
1939 if (LHSIt->start == RHSIt->end) {
1940 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1941 // We already know that this value number is going to be merged in
1942 // if coalescing succeeds. Just skip the liverange.
1943 if (++LHSIt == LHSEnd) break;
1945 // Otherwise, if this is a copy from the RHS, mark it as being merged
1947 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1948 if (LHSIt->contains(RHSIt->valno->def))
1949 // Here is an interesting situation:
1951 // vr1025 = copy vr1024
1956 // Even though vr1025 is copied from vr1024, it's not safe to
1957 // coalesced them since live range of vr1025 intersects the
1958 // def of vr1024. This happens because vr1025 is assigned the
1959 // value of the previous iteration of vr1024.
1961 EliminatedLHSVals.push_back(LHSIt->valno);
1963 // We know this entire LHS live range is okay, so skip it now.
1964 if (++LHSIt == LHSEnd) break;
1969 if (++RHSIt == RHSEnd) break;
1973 // If we got here, we know that the coalescing will be successful and that
1974 // the value numbers in EliminatedLHSVals will all be merged together. Since
1975 // the most common case is that EliminatedLHSVals has a single number, we
1976 // optimize for it: if there is more than one value, we merge them all into
1977 // the lowest numbered one, then handle the interval as if we were merging
1978 // with one value number.
1979 VNInfo *LHSValNo = NULL;
1980 if (EliminatedLHSVals.size() > 1) {
1981 // Loop through all the equal value numbers merging them into the smallest
1983 VNInfo *Smallest = EliminatedLHSVals[0];
1984 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1985 if (EliminatedLHSVals[i]->id < Smallest->id) {
1986 // Merge the current notion of the smallest into the smaller one.
1987 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1988 Smallest = EliminatedLHSVals[i];
1990 // Merge into the smallest.
1991 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1994 LHSValNo = Smallest;
1995 } else if (EliminatedLHSVals.empty()) {
1996 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1997 *tri_->getSuperRegisters(LHS.reg))
1998 // Imprecise sub-register information. Can't handle it.
2000 llvm_unreachable("No copies from the RHS?");
2002 LHSValNo = EliminatedLHSVals[0];
2005 // Okay, now that there is a single LHS value number that we're merging the
2006 // RHS into, update the value number info for the LHS to indicate that the
2007 // value number is defined where the RHS value number was.
2008 const VNInfo *VNI = RHS.getValNumInfo(0);
2009 LHSValNo->def = VNI->def;
2010 LHSValNo->setCopy(VNI->getCopy());
2012 // Okay, the final step is to loop over the RHS live intervals, adding them to
2014 if (VNI->hasPHIKill())
2015 LHSValNo->setHasPHIKill(true);
2016 LHS.addKills(LHSValNo, VNI->kills);
2017 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2019 LHS.ComputeJoinedWeight(RHS);
2021 // Update regalloc hint if both are virtual registers.
2022 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2023 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2024 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2025 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2026 if (RHSPref != LHSPref)
2027 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2030 // Update the liveintervals of sub-registers.
2031 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2032 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2033 li_->getOrCreateInterval(*AS).MergeInClobberRanges(LHS,
2034 li_->getVNInfoAllocator());
2039 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2040 /// returns false. Otherwise, if one of the intervals being joined is a
2041 /// physreg, this method always canonicalizes LHS to be it. The output
2042 /// "RHS" will not have been modified, so we can use this information
2043 /// below to update aliases.
2045 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2047 // Compute the final value assignment, assuming that the live ranges can be
2049 SmallVector<int, 16> LHSValNoAssignments;
2050 SmallVector<int, 16> RHSValNoAssignments;
2051 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2052 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2053 SmallVector<VNInfo*, 16> NewVNInfo;
2055 // If a live interval is a physical register, conservatively check if any
2056 // of its sub-registers is overlapping the live interval of the virtual
2057 // register. If so, do not coalesce.
2058 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2059 *tri_->getSubRegisters(LHS.reg)) {
2060 // If it's coalescing a virtual register to a physical register, estimate
2061 // its live interval length. This is the *cost* of scanning an entire live
2062 // interval. If the cost is low, we'll do an exhaustive check instead.
2064 // If this is something like this:
2072 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2073 // less conservative check. It's possible a sub-register is defined before
2074 // v1024 (or live in) and live out of BB1.
2075 if (RHS.containsOneValue() &&
2076 li_->intervalIsInOneMBB(RHS) &&
2077 li_->getApproximateInstructionCount(RHS) <= 10) {
2078 // Perform a more exhaustive check for some common cases.
2079 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2082 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2083 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2085 errs() << "Interfere with sub-register ";
2086 li_->getInterval(*SR).print(errs(), tri_);
2091 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2092 *tri_->getSubRegisters(RHS.reg)) {
2093 if (LHS.containsOneValue() &&
2094 li_->getApproximateInstructionCount(LHS) <= 10) {
2095 // Perform a more exhaustive check for some common cases.
2096 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2099 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2100 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2102 errs() << "Interfere with sub-register ";
2103 li_->getInterval(*SR).print(errs(), tri_);
2110 // Compute ultimate value numbers for the LHS and RHS values.
2111 if (RHS.containsOneValue()) {
2112 // Copies from a liveinterval with a single value are simple to handle and
2113 // very common, handle the special case here. This is important, because
2114 // often RHS is small and LHS is large (e.g. a physreg).
2116 // Find out if the RHS is defined as a copy from some value in the LHS.
2117 int RHSVal0DefinedFromLHS = -1;
2119 VNInfo *RHSValNoInfo = NULL;
2120 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2121 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2122 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2123 // If RHS is not defined as a copy from the LHS, we can use simpler and
2124 // faster checks to see if the live ranges are coalescable. This joiner
2125 // can't swap the LHS/RHS intervals though.
2126 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2127 return SimpleJoin(LHS, RHS);
2129 RHSValNoInfo = RHSValNoInfo0;
2132 // It was defined as a copy from the LHS, find out what value # it is.
2134 LHS.getLiveRangeContaining(li_->getPrevSlot(RHSValNoInfo0->def))->valno;
2135 RHSValID = RHSValNoInfo->id;
2136 RHSVal0DefinedFromLHS = RHSValID;
2139 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2140 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2141 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2143 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2144 // should now get updated.
2145 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2148 unsigned VN = VNI->id;
2149 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2150 if (LHSSrcReg != RHS.reg) {
2151 // If this is not a copy from the RHS, its value number will be
2152 // unmodified by the coalescing.
2153 NewVNInfo[VN] = VNI;
2154 LHSValNoAssignments[VN] = VN;
2155 } else if (RHSValID == -1) {
2156 // Otherwise, it is a copy from the RHS, and we don't already have a
2157 // value# for it. Keep the current value number, but remember it.
2158 LHSValNoAssignments[VN] = RHSValID = VN;
2159 NewVNInfo[VN] = RHSValNoInfo;
2160 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2162 // Otherwise, use the specified value #.
2163 LHSValNoAssignments[VN] = RHSValID;
2164 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2165 NewVNInfo[VN] = RHSValNoInfo;
2166 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2170 NewVNInfo[VN] = VNI;
2171 LHSValNoAssignments[VN] = VN;
2175 assert(RHSValID != -1 && "Didn't find value #?");
2176 RHSValNoAssignments[0] = RHSValID;
2177 if (RHSVal0DefinedFromLHS != -1) {
2178 // This path doesn't go through ComputeUltimateVN so just set
2180 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2183 // Loop over the value numbers of the LHS, seeing if any are defined from
2185 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2188 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2191 // DstReg is known to be a register in the LHS interval. If the src is
2192 // from the RHS interval, we can use its value #.
2193 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2196 // Figure out the value # from the RHS.
2197 LHSValsDefinedFromRHS[VNI]=
2198 RHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2201 // Loop over the value numbers of the RHS, seeing if any are defined from
2203 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2206 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2209 // DstReg is known to be a register in the RHS interval. If the src is
2210 // from the LHS interval, we can use its value #.
2211 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2214 // Figure out the value # from the LHS.
2215 RHSValsDefinedFromLHS[VNI]=
2216 LHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2219 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2220 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2221 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2223 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2226 unsigned VN = VNI->id;
2227 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2229 ComputeUltimateVN(VNI, NewVNInfo,
2230 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2231 LHSValNoAssignments, RHSValNoAssignments);
2233 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2236 unsigned VN = VNI->id;
2237 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2239 // If this value number isn't a copy from the LHS, it's a new number.
2240 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2241 NewVNInfo.push_back(VNI);
2242 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2246 ComputeUltimateVN(VNI, NewVNInfo,
2247 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2248 RHSValNoAssignments, LHSValNoAssignments);
2252 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2253 // interval lists to see if these intervals are coalescable.
2254 LiveInterval::const_iterator I = LHS.begin();
2255 LiveInterval::const_iterator IE = LHS.end();
2256 LiveInterval::const_iterator J = RHS.begin();
2257 LiveInterval::const_iterator JE = RHS.end();
2259 // Skip ahead until the first place of potential sharing.
2260 if (I->start < J->start) {
2261 I = std::upper_bound(I, IE, J->start);
2262 if (I != LHS.begin()) --I;
2263 } else if (J->start < I->start) {
2264 J = std::upper_bound(J, JE, I->start);
2265 if (J != RHS.begin()) --J;
2269 // Determine if these two live ranges overlap.
2271 if (I->start < J->start) {
2272 Overlaps = I->end > J->start;
2274 Overlaps = J->end > I->start;
2277 // If so, check value # info to determine if they are really different.
2279 // If the live range overlap will map to the same value number in the
2280 // result liverange, we can still coalesce them. If not, we can't.
2281 if (LHSValNoAssignments[I->valno->id] !=
2282 RHSValNoAssignments[J->valno->id])
2286 if (I->end < J->end) {
2295 // Update kill info. Some live ranges are extended due to copy coalescing.
2296 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2297 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2298 VNInfo *VNI = I->first;
2299 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2300 NewVNInfo[LHSValID]->removeKill(VNI->def);
2301 if (VNI->hasPHIKill())
2302 NewVNInfo[LHSValID]->setHasPHIKill(true);
2303 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2306 // Update kill info. Some live ranges are extended due to copy coalescing.
2307 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2308 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2309 VNInfo *VNI = I->first;
2310 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2311 NewVNInfo[RHSValID]->removeKill(VNI->def);
2312 if (VNI->hasPHIKill())
2313 NewVNInfo[RHSValID]->setHasPHIKill(true);
2314 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2317 // If we get here, we know that we can coalesce the live ranges. Ask the
2318 // intervals to coalesce themselves now.
2319 if ((RHS.ranges.size() > LHS.ranges.size() &&
2320 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2321 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2322 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2326 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2334 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2335 // depth of the basic block (the unsigned), and then on the MBB number.
2336 struct DepthMBBCompare {
2337 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2338 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2339 if (LHS.first > RHS.first) return true; // Deeper loops first
2340 return LHS.first == RHS.first &&
2341 LHS.second->getNumber() < RHS.second->getNumber();
2346 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2347 std::vector<CopyRec> &TryAgain) {
2348 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
2350 std::vector<CopyRec> VirtCopies;
2351 std::vector<CopyRec> PhysCopies;
2352 std::vector<CopyRec> ImpDefCopies;
2353 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2355 MachineInstr *Inst = MII++;
2357 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2358 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2359 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2360 DstReg = Inst->getOperand(0).getReg();
2361 SrcReg = Inst->getOperand(1).getReg();
2362 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2363 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
2364 DstReg = Inst->getOperand(0).getReg();
2365 SrcReg = Inst->getOperand(2).getReg();
2366 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2369 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2370 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2371 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2372 ImpDefCopies.push_back(CopyRec(Inst, 0));
2373 else if (SrcIsPhys || DstIsPhys)
2374 PhysCopies.push_back(CopyRec(Inst, 0));
2376 VirtCopies.push_back(CopyRec(Inst, 0));
2379 // Try coalescing implicit copies first, followed by copies to / from
2380 // physical registers, then finally copies from virtual registers to
2381 // virtual registers.
2382 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2383 CopyRec &TheCopy = ImpDefCopies[i];
2385 if (!JoinCopy(TheCopy, Again))
2387 TryAgain.push_back(TheCopy);
2389 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2390 CopyRec &TheCopy = PhysCopies[i];
2392 if (!JoinCopy(TheCopy, Again))
2394 TryAgain.push_back(TheCopy);
2396 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2397 CopyRec &TheCopy = VirtCopies[i];
2399 if (!JoinCopy(TheCopy, Again))
2401 TryAgain.push_back(TheCopy);
2405 void SimpleRegisterCoalescing::joinIntervals() {
2406 DEBUG(errs() << "********** JOINING INTERVALS ***********\n");
2408 std::vector<CopyRec> TryAgainList;
2409 if (loopInfo->empty()) {
2410 // If there are no loops in the function, join intervals in function order.
2411 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2413 CopyCoalesceInMBB(I, TryAgainList);
2415 // Otherwise, join intervals in inner loops before other intervals.
2416 // Unfortunately we can't just iterate over loop hierarchy here because
2417 // there may be more MBB's than BB's. Collect MBB's for sorting.
2419 // Join intervals in the function prolog first. We want to join physical
2420 // registers with virtual registers before the intervals got too long.
2421 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2422 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2423 MachineBasicBlock *MBB = I;
2424 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2427 // Sort by loop depth.
2428 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2430 // Finally, join intervals in loop nest order.
2431 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2432 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2435 // Joining intervals can allow other intervals to be joined. Iteratively join
2436 // until we make no progress.
2437 bool ProgressMade = true;
2438 while (ProgressMade) {
2439 ProgressMade = false;
2441 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2442 CopyRec &TheCopy = TryAgainList[i];
2447 bool Success = JoinCopy(TheCopy, Again);
2448 if (Success || !Again) {
2449 TheCopy.MI = 0; // Mark this one as done.
2450 ProgressMade = true;
2456 /// Return true if the two specified registers belong to different register
2457 /// classes. The registers may be either phys or virt regs.
2459 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2460 unsigned RegB) const {
2461 // Get the register classes for the first reg.
2462 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2463 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2464 "Shouldn't consider two physregs!");
2465 return !mri_->getRegClass(RegB)->contains(RegA);
2468 // Compare against the regclass for the second reg.
2469 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2470 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2471 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2472 return RegClassA != RegClassB;
2474 return !RegClassA->contains(RegB);
2477 /// lastRegisterUse - Returns the last use of the specific register between
2478 /// cycles Start and End or NULL if there are no uses.
2480 SimpleRegisterCoalescing::lastRegisterUse(LiveIndex Start,
2483 LiveIndex &UseIdx) const{
2484 UseIdx = LiveIndex();
2485 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2486 MachineOperand *LastUse = NULL;
2487 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2488 E = mri_->use_end(); I != E; ++I) {
2489 MachineOperand &Use = I.getOperand();
2490 MachineInstr *UseMI = Use.getParent();
2491 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2492 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2494 // Ignore identity copies.
2496 LiveIndex Idx = li_->getInstructionIndex(UseMI);
2497 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2499 UseIdx = li_->getUseIndex(Idx);
2505 LiveIndex s = Start;
2506 LiveIndex e = li_->getBaseIndex(li_->getPrevSlot(End));
2508 // Skip deleted instructions
2509 MachineInstr *MI = li_->getInstructionFromIndex(e);
2510 while (e != LiveIndex() && li_->getPrevIndex(e) >= s && !MI) {
2511 e = li_->getPrevIndex(e);
2512 MI = li_->getInstructionFromIndex(e);
2514 if (e < s || MI == NULL)
2517 // Ignore identity copies.
2518 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2519 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2521 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2522 MachineOperand &Use = MI->getOperand(i);
2523 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2524 tri_->regsOverlap(Use.getReg(), Reg)) {
2525 UseIdx = li_->getUseIndex(e);
2530 e = li_->getPrevIndex(e);
2537 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2538 if (TargetRegisterInfo::isPhysicalRegister(reg))
2539 errs() << tri_->getName(reg);
2541 errs() << "%reg" << reg;
2544 void SimpleRegisterCoalescing::releaseMemory() {
2545 JoinedCopies.clear();
2546 ReMatCopies.clear();
2550 /// Returns true if the given live interval is zero length.
2551 static bool isZeroLengthInterval(LiveInterval *li, LiveIntervals *li_) {
2552 for (LiveInterval::Ranges::const_iterator
2553 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2554 if (li_->getPrevIndex(i->end) > i->start)
2559 void SimpleRegisterCoalescing::CalculateSpillWeights() {
2560 SmallSet<unsigned, 4> Processed;
2561 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2562 mbbi != mbbe; ++mbbi) {
2563 MachineBasicBlock* MBB = mbbi;
2564 LiveIndex MBBEnd = li_->getMBBEndIdx(MBB);
2565 MachineLoop* loop = loopInfo->getLoopFor(MBB);
2566 unsigned loopDepth = loop ? loop->getLoopDepth() : 0;
2567 bool isExit = loop ? loop->isLoopExit(MBB) : false;
2569 for (MachineBasicBlock::iterator mii = MBB->begin(), mie = MBB->end();
2570 mii != mie; ++mii) {
2571 MachineInstr *MI = mii;
2573 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2574 const MachineOperand &mopi = MI->getOperand(i);
2575 if (!mopi.isReg() || mopi.getReg() == 0)
2577 unsigned Reg = mopi.getReg();
2578 if (!TargetRegisterInfo::isVirtualRegister(mopi.getReg()))
2580 // Multiple uses of reg by the same instruction. It should not
2581 // contribute to spill weight again.
2582 if (!Processed.insert(Reg))
2585 bool HasDef = mopi.isDef();
2586 bool HasUse = !HasDef;
2587 for (unsigned j = i+1; j != e; ++j) {
2588 const MachineOperand &mopj = MI->getOperand(j);
2589 if (!mopj.isReg() || mopj.getReg() != Reg)
2591 HasDef |= mopj.isDef();
2592 HasUse |= mopj.isUse();
2593 if (HasDef && HasUse)
2597 LiveInterval &RegInt = li_->getInterval(Reg);
2598 float Weight = li_->getSpillWeight(HasDef, HasUse, loopDepth);
2599 if (HasDef && isExit) {
2600 // Looks like this is a loop count variable update.
2602 li_->getDefIndex(li_->getInstructionIndex(MI));
2603 const LiveRange *DLR =
2604 li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
2605 if (DLR->end > MBBEnd)
2608 RegInt.weight += Weight;
2614 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2615 LiveInterval &LI = *I->second;
2616 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2617 // If the live interval length is essentially zero, i.e. in every live
2618 // range the use follows def immediately, it doesn't make sense to spill
2619 // it and hope it will be easier to allocate for this li.
2620 if (isZeroLengthInterval(&LI, li_)) {
2621 LI.weight = HUGE_VALF;
2625 bool isLoad = false;
2626 SmallVector<LiveInterval*, 4> SpillIs;
2627 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2628 // If all of the definitions of the interval are re-materializable,
2629 // it is a preferred candidate for spilling. If non of the defs are
2630 // loads, then it's potentially very cheap to re-materialize.
2631 // FIXME: this gets much more complicated once we support non-trivial
2632 // re-materialization.
2639 // Slightly prefer live interval that has been assigned a preferred reg.
2640 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2641 if (Hint.first || Hint.second)
2644 // Divide the weight of the interval by its size. This encourages
2645 // spilling of intervals that are large and have few uses, and
2646 // discourages spilling of small intervals with many uses.
2647 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2653 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2655 mri_ = &fn.getRegInfo();
2656 tm_ = &fn.getTarget();
2657 tri_ = tm_->getRegisterInfo();
2658 tii_ = tm_->getInstrInfo();
2659 li_ = &getAnalysis<LiveIntervals>();
2660 AA = &getAnalysis<AliasAnalysis>();
2661 loopInfo = &getAnalysis<MachineLoopInfo>();
2663 DEBUG(errs() << "********** SIMPLE REGISTER COALESCING **********\n"
2664 << "********** Function: "
2665 << ((Value*)mf_->getFunction())->getName() << '\n');
2667 allocatableRegs_ = tri_->getAllocatableSet(fn);
2668 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2669 E = tri_->regclass_end(); I != E; ++I)
2670 allocatableRCRegs_.insert(std::make_pair(*I,
2671 tri_->getAllocatableSet(fn, *I)));
2673 // Join (coalesce) intervals if requested.
2674 if (EnableJoining) {
2677 errs() << "********** INTERVALS POST JOINING **********\n";
2678 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2679 I->second->print(errs(), tri_);
2685 // Perform a final pass over the instructions and compute spill weights
2686 // and remove identity moves.
2687 SmallVector<unsigned, 4> DeadDefs;
2688 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2689 mbbi != mbbe; ++mbbi) {
2690 MachineBasicBlock* mbb = mbbi;
2691 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2693 MachineInstr *MI = mii;
2694 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2695 if (JoinedCopies.count(MI)) {
2696 // Delete all coalesced copies.
2697 bool DoDelete = true;
2698 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2699 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2700 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2701 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
2702 "Unrecognized copy instruction");
2703 DstReg = MI->getOperand(0).getReg();
2704 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2705 // Do not delete extract_subreg, insert_subreg of physical
2706 // registers unless the definition is dead. e.g.
2707 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2708 // or else the scavenger may complain. LowerSubregs will
2709 // change this to an IMPLICIT_DEF later.
2712 if (MI->registerDefIsDead(DstReg)) {
2713 LiveInterval &li = li_->getInterval(DstReg);
2714 if (!ShortenDeadCopySrcLiveRange(li, MI))
2715 ShortenDeadCopyLiveRange(li, MI);
2721 li_->RemoveMachineInstrFromMaps(MI);
2722 mii = mbbi->erase(mii);
2728 // Now check if this is a remat'ed def instruction which is now dead.
2729 if (ReMatDefs.count(MI)) {
2731 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2732 const MachineOperand &MO = MI->getOperand(i);
2735 unsigned Reg = MO.getReg();
2738 if (TargetRegisterInfo::isVirtualRegister(Reg))
2739 DeadDefs.push_back(Reg);
2742 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2743 !mri_->use_empty(Reg)) {
2749 while (!DeadDefs.empty()) {
2750 unsigned DeadDef = DeadDefs.back();
2751 DeadDefs.pop_back();
2752 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2754 li_->RemoveMachineInstrFromMaps(mii);
2755 mii = mbbi->erase(mii);
2761 // If the move will be an identity move delete it
2762 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2763 if (isMove && SrcReg == DstReg) {
2764 if (li_->hasInterval(SrcReg)) {
2765 LiveInterval &RegInt = li_->getInterval(SrcReg);
2766 // If def of this move instruction is dead, remove its live range
2767 // from the dstination register's live interval.
2768 if (MI->registerDefIsDead(DstReg)) {
2769 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2770 ShortenDeadCopyLiveRange(RegInt, MI);
2773 li_->RemoveMachineInstrFromMaps(MI);
2774 mii = mbbi->erase(mii);
2782 CalculateSpillWeights();
2788 /// print - Implement the dump method.
2789 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2793 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2794 return new SimpleRegisterCoalescing();
2797 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2798 DEFINING_FILE_FOR(SimpleRegisterCoalescing)