1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/LiveVariables.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/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
38 STATISTIC(numJoins , "Number of interval joins performed");
39 STATISTIC(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends , "Number of copies extended");
41 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
42 STATISTIC(numAborts , "Number of times interval joining aborted");
44 char SimpleRegisterCoalescing::ID = 0;
47 EnableJoining("join-liveintervals",
48 cl::desc("Coalesce copies (default=true)"),
52 NewHeuristic("new-coalescer-heuristic",
53 cl::desc("Use new coalescer heuristic"),
56 RegisterPass<SimpleRegisterCoalescing>
57 X("simple-register-coalescing", "Simple Register Coalescing");
59 // Declare that we implement the RegisterCoalescer interface
60 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
63 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
65 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addPreserved<LiveIntervals>();
67 AU.addPreserved<MachineLoopInfo>();
68 AU.addPreservedID(MachineDominatorsID);
69 AU.addPreservedID(PHIEliminationID);
70 AU.addPreservedID(TwoAddressInstructionPassID);
71 AU.addRequired<LiveVariables>();
72 AU.addRequired<LiveIntervals>();
73 AU.addRequired<MachineLoopInfo>();
74 MachineFunctionPass::getAnalysisUsage(AU);
77 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
78 /// being the source and IntB being the dest, thus this defines a value number
79 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
80 /// see if we can merge these two pieces of B into a single value number,
81 /// eliminating a copy. For example:
85 /// B1 = A3 <- this copy
87 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
88 /// value number to be replaced with B0 (which simplifies the B liveinterval).
90 /// This returns true if an interval was modified.
92 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
94 MachineInstr *CopyMI) {
95 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
97 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
99 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
100 VNInfo *BValNo = BLR->valno;
102 // Get the location that B is defined at. Two options: either this value has
103 // an unknown definition point or it is defined at CopyIdx. If unknown, we
105 if (!BValNo->copy) return false;
106 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
108 // AValNo is the value number in A that defines the copy, A3 in the example.
109 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
110 VNInfo *AValNo = ALR->valno;
112 // If AValNo is defined as a copy from IntB, we can potentially process this.
113 // Get the instruction that defines this value number.
114 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
115 if (!SrcReg) return false; // Not defined by a copy.
117 // If the value number is not defined by a copy instruction, ignore it.
119 // If the source register comes from an interval other than IntB, we can't
121 if (SrcReg != IntB.reg) return false;
123 // Get the LiveRange in IntB that this value number starts with.
124 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
126 // Make sure that the end of the live range is inside the same block as
128 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
130 ValLREndInst->getParent() != CopyMI->getParent()) return false;
132 // Okay, we now know that ValLR ends in the same block that the CopyMI
133 // live-range starts. If there are no intervening live ranges between them in
134 // IntB, we can merge them.
135 if (ValLR+1 != BLR) return false;
137 // If a live interval is a physical register, conservatively check if any
138 // of its sub-registers is overlapping the live interval of the virtual
139 // register. If so, do not coalesce.
140 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
141 *tri_->getSubRegisters(IntB.reg)) {
142 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
143 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
144 DOUT << "Interfere with sub-register ";
145 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
150 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
152 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
153 // We are about to delete CopyMI, so need to remove it as the 'instruction
154 // that defines this value #'. Update the the valnum with the new defining
156 BValNo->def = FillerStart;
159 // Okay, we can merge them. We need to insert a new liverange:
160 // [ValLR.end, BLR.begin) of either value number, then we merge the
161 // two value numbers.
162 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
164 // If the IntB live range is assigned to a physical register, and if that
165 // physreg has aliases,
166 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
167 // Update the liveintervals of sub-registers.
168 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
169 LiveInterval &AliasLI = li_->getInterval(*AS);
170 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
171 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
175 // Okay, merge "B1" into the same value number as "B0".
176 if (BValNo != ValLR->valno)
177 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
178 DOUT << " result = "; IntB.print(DOUT, tri_);
181 // If the source instruction was killing the source register before the
182 // merge, unset the isKill marker given the live range has been extended.
183 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
185 ValLREndInst->getOperand(UIdx).setIsKill(false);
191 /// HasOtherReachingDefs - Return true if there are definitions of IntB
192 /// other than BValNo val# that can reach uses of AValno val# of IntA.
193 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
197 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
199 if (AI->valno != AValNo) continue;
200 LiveInterval::Ranges::iterator BI =
201 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
202 if (BI != IntB.ranges.begin())
204 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
205 if (BI->valno == BValNo)
207 if (BI->start <= AI->start && BI->end > AI->start)
209 if (BI->start > AI->start && BI->start < AI->end)
216 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
217 /// being the source and IntB being the dest, thus this defines a value number
218 /// in IntB. If the source value number (in IntA) is defined by a commutable
219 /// instruction and its other operand is coalesced to the copy dest register,
220 /// see if we can transform the copy into a noop by commuting the definition. For
223 /// A3 = op A2 B0<kill>
225 /// B1 = A3 <- this copy
227 /// = op A3 <- more uses
231 /// B2 = op B0 A2<kill>
233 /// B1 = B2 <- now an identify copy
235 /// = op B2 <- more uses
237 /// This returns true if an interval was modified.
239 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
241 MachineInstr *CopyMI) {
242 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
244 // FIXME: For now, only eliminate the copy by commuting its def when the
245 // source register is a virtual register. We want to guard against cases
246 // where the copy is a back edge copy and commuting the def lengthen the
247 // live interval of the source register to the entire loop.
248 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
251 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
252 // the example above.
253 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
254 VNInfo *BValNo = BLR->valno;
256 // Get the location that B is defined at. Two options: either this value has
257 // an unknown definition point or it is defined at CopyIdx. If unknown, we
259 if (!BValNo->copy) return false;
260 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
262 // AValNo is the value number in A that defines the copy, A3 in the example.
263 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
264 VNInfo *AValNo = ALR->valno;
265 // If other defs can reach uses of this def, then it's not safe to perform
267 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
269 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
270 const TargetInstrDesc &TID = DefMI->getDesc();
272 if (!TID.isCommutable() ||
273 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
276 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
277 unsigned NewReg = NewDstMO.getReg();
278 if (NewReg != IntB.reg || !NewDstMO.isKill())
281 // Make sure there are no other definitions of IntB that would reach the
282 // uses which the new definition can reach.
283 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
286 // If some of the uses of IntA.reg is already coalesced away, return false.
287 // It's not possible to determine whether it's safe to perform the coalescing.
288 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
289 UE = mri_->use_end(); UI != UE; ++UI) {
290 MachineInstr *UseMI = &*UI;
291 unsigned UseIdx = li_->getInstructionIndex(UseMI);
292 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
293 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
297 // At this point we have decided that it is legal to do this
298 // transformation. Start by commuting the instruction.
299 MachineBasicBlock *MBB = DefMI->getParent();
300 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
303 if (NewMI != DefMI) {
304 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
305 MBB->insert(DefMI, NewMI);
308 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
309 NewMI->getOperand(OpIdx).setIsKill();
311 bool BHasPHIKill = BValNo->hasPHIKill;
312 SmallVector<VNInfo*, 4> BDeadValNos;
313 SmallVector<unsigned, 4> BKills;
314 std::map<unsigned, unsigned> BExtend;
316 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
325 // then do not add kills of A to the newly created B interval.
326 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
328 BExtend[ALR->end] = BLR->end;
330 // Update uses of IntA of the specific Val# with IntB.
331 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
332 UE = mri_->use_end(); UI != UE;) {
333 MachineOperand &UseMO = UI.getOperand();
334 MachineInstr *UseMI = &*UI;
336 if (JoinedCopies.count(UseMI))
338 unsigned UseIdx = li_->getInstructionIndex(UseMI);
339 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
340 if (ULR->valno != AValNo)
342 UseMO.setReg(NewReg);
345 if (UseMO.isKill()) {
347 UseMO.setIsKill(false);
349 BKills.push_back(li_->getUseIndex(UseIdx)+1);
351 unsigned SrcReg, DstReg;
352 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
354 if (DstReg == IntB.reg) {
355 // This copy will become a noop. If it's defining a new val#,
356 // remove that val# as well. However this live range is being
357 // extended to the end of the existing live range defined by the copy.
358 unsigned DefIdx = li_->getDefIndex(UseIdx);
359 LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
360 BHasPHIKill |= DLR->valno->hasPHIKill;
361 assert(DLR->valno->def == DefIdx);
362 BDeadValNos.push_back(DLR->valno);
363 BExtend[DLR->start] = DLR->end;
364 JoinedCopies.insert(UseMI);
365 // If this is a kill but it's going to be removed, the last use
366 // of the same val# is the new kill.
372 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
373 // simply extend BLR if CopyMI doesn't end the range.
374 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
376 IntB.removeValNo(BValNo);
377 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
378 IntB.removeValNo(BDeadValNos[i]);
379 VNInfo *ValNo = IntB.getNextValue(AValNo->def, 0, li_->getVNInfoAllocator());
380 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
382 if (AI->valno != AValNo) continue;
383 unsigned End = AI->end;
384 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
385 if (EI != BExtend.end())
387 IntB.addRange(LiveRange(AI->start, End, ValNo));
389 IntB.addKills(ValNo, BKills);
390 ValNo->hasPHIKill = BHasPHIKill;
392 DOUT << " result = "; IntB.print(DOUT, tri_);
395 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
396 IntA.removeValNo(AValNo);
397 DOUT << " result = "; IntA.print(DOUT, tri_);
404 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
406 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
408 MachineBasicBlock *MBB = CopyMI->getParent();
409 const MachineLoop *L = loopInfo->getLoopFor(MBB);
412 if (MBB != L->getLoopLatch())
415 LiveInterval &LI = li_->getInterval(DstReg);
416 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
417 LiveInterval::const_iterator DstLR =
418 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
419 if (DstLR == LI.end())
421 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
422 if (DstLR->valno->kills.size() == 1 &&
423 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
428 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
429 /// update the subregister number if it is not zero. If DstReg is a
430 /// physical register and the existing subregister number of the def / use
431 /// being updated is not zero, make sure to set it to the correct physical
434 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
436 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
437 if (DstIsPhys && SubIdx) {
438 // Figure out the real physical register we are updating with.
439 DstReg = tri_->getSubReg(DstReg, SubIdx);
443 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
444 E = mri_->reg_end(); I != E; ) {
445 MachineOperand &O = I.getOperand();
446 MachineInstr *UseMI = &*I;
449 unsigned UseSubIdx = O.getSubReg();
450 unsigned UseDstReg = DstReg;
452 UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
456 unsigned OldSubIdx = O.getSubReg();
457 // Sub-register indexes goes from small to large. e.g.
458 // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
459 // EAX: 0 -> AL, 1 -> AH, 2 -> AX
460 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
461 // sub-register 2 is also AX.
462 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
463 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
466 // Remove would-be duplicated kill marker.
467 if (O.isKill() && UseMI->killsRegister(DstReg))
474 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
475 /// due to live range lengthening as the result of coalescing.
476 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
478 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
479 UE = mri_->use_end(); UI != UE; ++UI) {
480 MachineOperand &UseMO = UI.getOperand();
481 if (UseMO.isKill()) {
482 MachineInstr *UseMI = UseMO.getParent();
484 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
486 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
487 if (JoinedCopies.count(UseMI))
489 LiveInterval::const_iterator UI = LI.FindLiveRangeContaining(UseIdx);
490 assert(UI != LI.end());
491 if (!LI.isKill(UI->valno, UseIdx+1))
492 UseMO.setIsKill(false);
497 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
498 /// from a physical register live interval as well as from the live intervals
499 /// of its sub-registers.
500 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
501 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
502 li.removeRange(Start, End, true);
503 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
504 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
505 if (!li_->hasInterval(*SR))
507 LiveInterval &sli = li_->getInterval(*SR);
508 unsigned RemoveEnd = Start;
509 while (RemoveEnd != End) {
510 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
513 RemoveEnd = (LR->end < End) ? LR->end : End;
514 sli.removeRange(Start, RemoveEnd, true);
521 /// removeIntervalIfEmpty - Check if the live interval of a physical register
522 /// is empty, if so remove it and also remove the empty intervals of its
524 static void removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
525 const TargetRegisterInfo *tri_) {
527 li_->removeInterval(li.reg);
528 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
529 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
530 if (!li_->hasInterval(*SR))
532 LiveInterval &sli = li_->getInterval(*SR);
534 li_->removeInterval(*SR);
539 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
541 void SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
542 MachineInstr *CopyMI) {
543 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
544 LiveInterval::iterator MLR =
545 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
547 return; // Already removed by ShortenDeadCopySrcLiveRange.
548 unsigned RemoveStart = MLR->start;
549 unsigned RemoveEnd = MLR->end;
550 // Remove the liverange that's defined by this.
551 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
552 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
553 removeIntervalIfEmpty(li, li_, tri_);
557 /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
558 /// extended by a dead copy. Mark the last use (if any) of the val# as kill
559 /// as ends the live range there. If there isn't another use, then this
560 /// live range is dead.
562 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
563 MachineInstr *CopyMI) {
564 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
566 // FIXME: special case: function live in. It can be a general case if the
567 // first instruction index starts at > 0 value.
568 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
569 // Live-in to the function but dead. Remove it from entry live-in set.
570 mf_->begin()->removeLiveIn(li.reg);
571 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
572 removeRange(li, LR->start, LR->end, li_, tri_);
573 removeIntervalIfEmpty(li, li_, tri_);
577 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
579 // Livein but defined by a phi.
582 unsigned RemoveStart = LR->start;
583 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
584 if (LR->end > RemoveEnd)
585 // More uses past this copy? Nothing to do.
589 MachineOperand *LastUse =
590 lastRegisterUse(LR->start, CopyIdx-1, li.reg, LastUseIdx);
592 // There are uses before the copy, just shorten the live range to the end
594 LastUse->setIsKill();
595 MachineInstr *LastUseMI = LastUse->getParent();
596 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
597 unsigned SrcReg, DstReg;
598 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
600 // Last use is itself an identity code.
601 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
602 LastUseMI->getOperand(DeadIdx).setIsDead();
608 MachineBasicBlock *CopyMBB = CopyMI->getParent();
609 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
610 if (LR->start <= MBBStart && LR->end > MBBStart) {
611 if (LR->start == 0) {
612 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
613 // Live-in to the function but dead. Remove it from entry live-in set.
614 mf_->begin()->removeLiveIn(li.reg);
616 removeRange(li, LR->start, LR->end, li_, tri_);
617 // FIXME: Shorten intervals in BBs that reaches this BB.
619 // Not livein into BB.
620 MachineInstr *DefMI =
621 li_->getInstructionFromIndex(li_->getDefIndex(RemoveStart));
622 if (DefMI && DefMI != CopyMI) {
623 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
625 DefMI->getOperand(DeadIdx).setIsDead();
626 // A dead def should have a single cycle interval.
630 removeRange(li, RemoveStart, LR->end, li_, tri_);
633 removeIntervalIfEmpty(li, li_, tri_);
636 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
637 /// which are the src/dst of the copy instruction CopyMI. This returns true
638 /// if the copy was successfully coalesced away. If it is not currently
639 /// possible to coalesce this interval, but it may be possible if other
640 /// things get coalesced, then it returns true by reference in 'Again'.
641 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
642 MachineInstr *CopyMI = TheCopy.MI;
645 if (JoinedCopies.count(CopyMI))
646 return false; // Already done.
648 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
652 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
655 DstReg = CopyMI->getOperand(0).getReg();
656 SrcReg = CopyMI->getOperand(1).getReg();
657 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
658 assert(0 && "Unrecognized copy instruction!");
662 // If they are already joined we continue.
663 if (SrcReg == DstReg) {
664 DOUT << "\tCopy already coalesced.\n";
665 return false; // Not coalescable.
668 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
669 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
671 // If they are both physical registers, we cannot join them.
672 if (SrcIsPhys && DstIsPhys) {
673 DOUT << "\tCan not coalesce physregs.\n";
674 return false; // Not coalescable.
677 // We only join virtual registers with allocatable physical registers.
678 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
679 DOUT << "\tSrc reg is unallocatable physreg.\n";
680 return false; // Not coalescable.
682 if (DstIsPhys && !allocatableRegs_[DstReg]) {
683 DOUT << "\tDst reg is unallocatable physreg.\n";
684 return false; // Not coalescable.
687 unsigned RealDstReg = 0;
689 SubIdx = CopyMI->getOperand(2).getImm();
691 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
692 // coalesced with AX.
693 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
695 } else if (DstIsPhys) {
696 // If this is a extract_subreg where dst is a physical register, e.g.
697 // cl = EXTRACT_SUBREG reg1024, 1
698 // then create and update the actual physical register allocated to RHS.
699 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
700 for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
701 unsigned SR = *SRs; ++SRs) {
702 if (DstReg == tri_->getSubReg(SR, SubIdx) &&
708 assert(RealDstReg && "Invalid extra_subreg instruction!");
710 // For this type of EXTRACT_SUBREG, conservatively
711 // check if the live interval of the source register interfere with the
712 // actual super physical register we are trying to coalesce with.
713 LiveInterval &RHS = li_->getInterval(SrcReg);
714 if (li_->hasInterval(RealDstReg) &&
715 RHS.overlaps(li_->getInterval(RealDstReg))) {
716 DOUT << "Interfere with register ";
717 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
718 return false; // Not coalescable
720 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
721 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
722 DOUT << "Interfere with sub-register ";
723 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
724 return false; // Not coalescable
728 unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
729 unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
730 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
731 unsigned Threshold = allocatableRCRegs_[RC].count();
732 // Be conservative. If both sides are virtual registers, do not coalesce
733 // if this will cause a high use density interval to target a smaller set
735 if (DstSize > Threshold || SrcSize > Threshold) {
736 LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
737 LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
738 if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
739 Again = true; // May be possible to coalesce later.
744 } else if (differingRegisterClasses(SrcReg, DstReg)) {
745 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
746 // with another? If it's the resulting destination register, then
747 // the subidx must be propagated to uses (but only those defined
748 // by the EXTRACT_SUBREG). If it's being coalesced into another
749 // register, it should be safe because register is assumed to have
750 // the register class of the super-register.
752 // If they are not of the same register class, we cannot join them.
753 DOUT << "\tSrc/Dest are different register classes.\n";
754 // Allow the coalescer to try again in case either side gets coalesced to
755 // a physical register that's compatible with the other side. e.g.
756 // r1024 = MOV32to32_ r1025
757 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
758 Again = true; // May be possible to coalesce later.
762 LiveInterval &SrcInt = li_->getInterval(SrcReg);
763 LiveInterval &DstInt = li_->getInterval(DstReg);
764 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
765 "Register mapping is horribly broken!");
767 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
768 DOUT << " and "; DstInt.print(DOUT, tri_);
771 // Check if it is necessary to propagate "isDead" property.
772 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
773 bool isDead = mopd->isDead();
775 // We need to be careful about coalescing a source physical register with a
776 // virtual register. Once the coalescing is done, it cannot be broken and
777 // these are not spillable! If the destination interval uses are far away,
778 // think twice about coalescing them!
779 if (!isDead && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
780 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
781 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
782 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
783 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
784 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
785 if (TheCopy.isBackEdge)
786 Threshold *= 2; // Favors back edge copies.
788 // If the virtual register live interval is long but it has low use desity,
789 // do not join them, instead mark the physical register as its allocation
791 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
792 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
793 if (Length > Threshold &&
794 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
795 JoinVInt.preference = JoinPReg;
797 DOUT << "\tMay tie down a physical register, abort!\n";
798 Again = true; // May be possible to coalesce later.
803 // Okay, attempt to join these two intervals. On failure, this returns false.
804 // Otherwise, if one of the intervals being joined is a physreg, this method
805 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
806 // been modified, so we can use this information below to update aliases.
807 bool Swapped = false;
808 if (!JoinIntervals(DstInt, SrcInt, Swapped)) {
809 // Coalescing failed.
811 // If we can eliminate the copy without merging the live ranges, do so now.
813 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
814 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
815 JoinedCopies.insert(CopyMI);
819 // Otherwise, we are unable to join the intervals.
820 DOUT << "Interference!\n";
821 Again = true; // May be possible to coalesce later.
825 LiveInterval *ResSrcInt = &SrcInt;
826 LiveInterval *ResDstInt = &DstInt;
828 std::swap(SrcReg, DstReg);
829 std::swap(ResSrcInt, ResDstInt);
831 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
832 "LiveInterval::join didn't work right!");
834 // If we're about to merge live ranges into a physical register live range,
835 // we have to update any aliased register's live ranges to indicate that they
836 // have clobbered values for this range.
837 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
838 // If this is a extract_subreg where dst is a physical register, e.g.
839 // cl = EXTRACT_SUBREG reg1024, 1
840 // then create and update the actual physical register allocated to RHS.
842 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
843 SmallSet<const VNInfo*, 4> CopiedValNos;
844 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
845 E = ResSrcInt->ranges.end(); I != E; ++I) {
846 LiveInterval::const_iterator DstLR =
847 ResDstInt->FindLiveRangeContaining(I->start);
848 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
849 const VNInfo *DstValNo = DstLR->valno;
850 if (CopiedValNos.insert(DstValNo)) {
851 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
852 li_->getVNInfoAllocator());
853 ValNo->hasPHIKill = DstValNo->hasPHIKill;
854 RealDstInt.addKills(ValNo, DstValNo->kills);
855 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
861 // Update the liveintervals of sub-registers.
862 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
863 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
864 li_->getVNInfoAllocator());
866 // Merge use info if the destination is a virtual register.
867 LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
868 LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
869 dVI.NumUses += sVI.NumUses;
872 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
873 // larger super-register.
874 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
876 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
877 std::swap(SrcReg, DstReg);
878 std::swap(ResSrcInt, ResDstInt);
883 // Add all copies that define val# in the source interval into the queue.
884 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
885 e = ResSrcInt->vni_end(); i != e; ++i) {
886 const VNInfo *vni = *i;
887 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
889 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
890 unsigned NewSrcReg, NewDstReg;
892 JoinedCopies.count(CopyMI) == 0 &&
893 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
894 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
895 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
896 isBackEdgeCopy(CopyMI, DstReg)));
901 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
904 // Remember to delete the copy instruction.
905 JoinedCopies.insert(CopyMI);
907 // Some live range has been lengthened due to colaescing, eliminate the
908 // unnecessary kills.
909 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
910 if (TargetRegisterInfo::isVirtualRegister(DstReg))
911 RemoveUnnecessaryKills(DstReg, *ResDstInt);
913 // SrcReg is guarateed to be the register whose live interval that is
915 li_->removeInterval(SrcReg);
916 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
922 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
923 /// compute what the resultant value numbers for each value in the input two
924 /// ranges will be. This is complicated by copies between the two which can
925 /// and will commonly cause multiple value numbers to be merged into one.
927 /// VN is the value number that we're trying to resolve. InstDefiningValue
928 /// keeps track of the new InstDefiningValue assignment for the result
929 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
930 /// whether a value in this or other is a copy from the opposite set.
931 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
932 /// already been assigned.
934 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
935 /// contains the value number the copy is from.
937 static unsigned ComputeUltimateVN(VNInfo *VNI,
938 SmallVector<VNInfo*, 16> &NewVNInfo,
939 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
940 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
941 SmallVector<int, 16> &ThisValNoAssignments,
942 SmallVector<int, 16> &OtherValNoAssignments) {
943 unsigned VN = VNI->id;
945 // If the VN has already been computed, just return it.
946 if (ThisValNoAssignments[VN] >= 0)
947 return ThisValNoAssignments[VN];
948 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
950 // If this val is not a copy from the other val, then it must be a new value
951 // number in the destination.
952 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
953 if (I == ThisFromOther.end()) {
954 NewVNInfo.push_back(VNI);
955 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
957 VNInfo *OtherValNo = I->second;
959 // Otherwise, this *is* a copy from the RHS. If the other side has already
960 // been computed, return it.
961 if (OtherValNoAssignments[OtherValNo->id] >= 0)
962 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
964 // Mark this value number as currently being computed, then ask what the
965 // ultimate value # of the other value is.
966 ThisValNoAssignments[VN] = -2;
967 unsigned UltimateVN =
968 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
969 OtherValNoAssignments, ThisValNoAssignments);
970 return ThisValNoAssignments[VN] = UltimateVN;
973 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
974 return std::find(V.begin(), V.end(), Val) != V.end();
977 /// SimpleJoin - Attempt to joint the specified interval into this one. The
978 /// caller of this method must guarantee that the RHS only contains a single
979 /// value number and that the RHS is not defined by a copy from this
980 /// interval. This returns false if the intervals are not joinable, or it
981 /// joins them and returns true.
982 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
983 assert(RHS.containsOneValue());
985 // Some number (potentially more than one) value numbers in the current
986 // interval may be defined as copies from the RHS. Scan the overlapping
987 // portions of the LHS and RHS, keeping track of this and looking for
988 // overlapping live ranges that are NOT defined as copies. If these exist, we
991 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
992 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
994 if (LHSIt->start < RHSIt->start) {
995 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
996 if (LHSIt != LHS.begin()) --LHSIt;
997 } else if (RHSIt->start < LHSIt->start) {
998 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
999 if (RHSIt != RHS.begin()) --RHSIt;
1002 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1005 // Determine if these live intervals overlap.
1006 bool Overlaps = false;
1007 if (LHSIt->start <= RHSIt->start)
1008 Overlaps = LHSIt->end > RHSIt->start;
1010 Overlaps = RHSIt->end > LHSIt->start;
1012 // If the live intervals overlap, there are two interesting cases: if the
1013 // LHS interval is defined by a copy from the RHS, it's ok and we record
1014 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1015 // coalesce these live ranges and we bail out.
1017 // If we haven't already recorded that this value # is safe, check it.
1018 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1019 // Copy from the RHS?
1020 unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
1021 if (SrcReg != RHS.reg)
1022 return false; // Nope, bail out.
1024 EliminatedLHSVals.push_back(LHSIt->valno);
1027 // We know this entire LHS live range is okay, so skip it now.
1028 if (++LHSIt == LHSEnd) break;
1032 if (LHSIt->end < RHSIt->end) {
1033 if (++LHSIt == LHSEnd) break;
1035 // One interesting case to check here. It's possible that we have
1036 // something like "X3 = Y" which defines a new value number in the LHS,
1037 // and is the last use of this liverange of the RHS. In this case, we
1038 // want to notice this copy (so that it gets coalesced away) even though
1039 // the live ranges don't actually overlap.
1040 if (LHSIt->start == RHSIt->end) {
1041 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1042 // We already know that this value number is going to be merged in
1043 // if coalescing succeeds. Just skip the liverange.
1044 if (++LHSIt == LHSEnd) break;
1046 // Otherwise, if this is a copy from the RHS, mark it as being merged
1048 if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
1049 EliminatedLHSVals.push_back(LHSIt->valno);
1051 // We know this entire LHS live range is okay, so skip it now.
1052 if (++LHSIt == LHSEnd) break;
1057 if (++RHSIt == RHSEnd) break;
1061 // If we got here, we know that the coalescing will be successful and that
1062 // the value numbers in EliminatedLHSVals will all be merged together. Since
1063 // the most common case is that EliminatedLHSVals has a single number, we
1064 // optimize for it: if there is more than one value, we merge them all into
1065 // the lowest numbered one, then handle the interval as if we were merging
1066 // with one value number.
1068 if (EliminatedLHSVals.size() > 1) {
1069 // Loop through all the equal value numbers merging them into the smallest
1071 VNInfo *Smallest = EliminatedLHSVals[0];
1072 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1073 if (EliminatedLHSVals[i]->id < Smallest->id) {
1074 // Merge the current notion of the smallest into the smaller one.
1075 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1076 Smallest = EliminatedLHSVals[i];
1078 // Merge into the smallest.
1079 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1082 LHSValNo = Smallest;
1084 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1085 LHSValNo = EliminatedLHSVals[0];
1088 // Okay, now that there is a single LHS value number that we're merging the
1089 // RHS into, update the value number info for the LHS to indicate that the
1090 // value number is defined where the RHS value number was.
1091 const VNInfo *VNI = RHS.getValNumInfo(0);
1092 LHSValNo->def = VNI->def;
1093 LHSValNo->copy = VNI->copy;
1095 // Okay, the final step is to loop over the RHS live intervals, adding them to
1097 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1098 LHS.addKills(LHSValNo, VNI->kills);
1099 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1100 LHS.weight += RHS.weight;
1101 if (RHS.preference && !LHS.preference)
1102 LHS.preference = RHS.preference;
1107 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1108 /// returns false. Otherwise, if one of the intervals being joined is a
1109 /// physreg, this method always canonicalizes LHS to be it. The output
1110 /// "RHS" will not have been modified, so we can use this information
1111 /// below to update aliases.
1112 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1113 LiveInterval &RHS, bool &Swapped) {
1114 // Compute the final value assignment, assuming that the live ranges can be
1116 SmallVector<int, 16> LHSValNoAssignments;
1117 SmallVector<int, 16> RHSValNoAssignments;
1118 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1119 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1120 SmallVector<VNInfo*, 16> NewVNInfo;
1122 // If a live interval is a physical register, conservatively check if any
1123 // of its sub-registers is overlapping the live interval of the virtual
1124 // register. If so, do not coalesce.
1125 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1126 *tri_->getSubRegisters(LHS.reg)) {
1127 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1128 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1129 DOUT << "Interfere with sub-register ";
1130 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1133 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1134 *tri_->getSubRegisters(RHS.reg)) {
1135 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1136 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1137 DOUT << "Interfere with sub-register ";
1138 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1143 // Compute ultimate value numbers for the LHS and RHS values.
1144 if (RHS.containsOneValue()) {
1145 // Copies from a liveinterval with a single value are simple to handle and
1146 // very common, handle the special case here. This is important, because
1147 // often RHS is small and LHS is large (e.g. a physreg).
1149 // Find out if the RHS is defined as a copy from some value in the LHS.
1150 int RHSVal0DefinedFromLHS = -1;
1152 VNInfo *RHSValNoInfo = NULL;
1153 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1154 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1155 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1156 // If RHS is not defined as a copy from the LHS, we can use simpler and
1157 // faster checks to see if the live ranges are coalescable. This joiner
1158 // can't swap the LHS/RHS intervals though.
1159 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1160 return SimpleJoin(LHS, RHS);
1162 RHSValNoInfo = RHSValNoInfo0;
1165 // It was defined as a copy from the LHS, find out what value # it is.
1166 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1167 RHSValID = RHSValNoInfo->id;
1168 RHSVal0DefinedFromLHS = RHSValID;
1171 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1172 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1173 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1175 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1176 // should now get updated.
1177 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1180 unsigned VN = VNI->id;
1181 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1182 if (LHSSrcReg != RHS.reg) {
1183 // If this is not a copy from the RHS, its value number will be
1184 // unmodified by the coalescing.
1185 NewVNInfo[VN] = VNI;
1186 LHSValNoAssignments[VN] = VN;
1187 } else if (RHSValID == -1) {
1188 // Otherwise, it is a copy from the RHS, and we don't already have a
1189 // value# for it. Keep the current value number, but remember it.
1190 LHSValNoAssignments[VN] = RHSValID = VN;
1191 NewVNInfo[VN] = RHSValNoInfo;
1192 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1194 // Otherwise, use the specified value #.
1195 LHSValNoAssignments[VN] = RHSValID;
1196 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1197 NewVNInfo[VN] = RHSValNoInfo;
1198 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1202 NewVNInfo[VN] = VNI;
1203 LHSValNoAssignments[VN] = VN;
1207 assert(RHSValID != -1 && "Didn't find value #?");
1208 RHSValNoAssignments[0] = RHSValID;
1209 if (RHSVal0DefinedFromLHS != -1) {
1210 // This path doesn't go through ComputeUltimateVN so just set
1212 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1215 // Loop over the value numbers of the LHS, seeing if any are defined from
1217 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1220 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1223 // DstReg is known to be a register in the LHS interval. If the src is
1224 // from the RHS interval, we can use its value #.
1225 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1228 // Figure out the value # from the RHS.
1229 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1232 // Loop over the value numbers of the RHS, seeing if any are defined from
1234 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1237 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1240 // DstReg is known to be a register in the RHS interval. If the src is
1241 // from the LHS interval, we can use its value #.
1242 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1245 // Figure out the value # from the LHS.
1246 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1249 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1250 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1251 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1253 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1256 unsigned VN = VNI->id;
1257 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1259 ComputeUltimateVN(VNI, NewVNInfo,
1260 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1261 LHSValNoAssignments, RHSValNoAssignments);
1263 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1266 unsigned VN = VNI->id;
1267 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1269 // If this value number isn't a copy from the LHS, it's a new number.
1270 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1271 NewVNInfo.push_back(VNI);
1272 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1276 ComputeUltimateVN(VNI, NewVNInfo,
1277 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1278 RHSValNoAssignments, LHSValNoAssignments);
1282 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1283 // interval lists to see if these intervals are coalescable.
1284 LiveInterval::const_iterator I = LHS.begin();
1285 LiveInterval::const_iterator IE = LHS.end();
1286 LiveInterval::const_iterator J = RHS.begin();
1287 LiveInterval::const_iterator JE = RHS.end();
1289 // Skip ahead until the first place of potential sharing.
1290 if (I->start < J->start) {
1291 I = std::upper_bound(I, IE, J->start);
1292 if (I != LHS.begin()) --I;
1293 } else if (J->start < I->start) {
1294 J = std::upper_bound(J, JE, I->start);
1295 if (J != RHS.begin()) --J;
1299 // Determine if these two live ranges overlap.
1301 if (I->start < J->start) {
1302 Overlaps = I->end > J->start;
1304 Overlaps = J->end > I->start;
1307 // If so, check value # info to determine if they are really different.
1309 // If the live range overlap will map to the same value number in the
1310 // result liverange, we can still coalesce them. If not, we can't.
1311 if (LHSValNoAssignments[I->valno->id] !=
1312 RHSValNoAssignments[J->valno->id])
1316 if (I->end < J->end) {
1325 // Update kill info. Some live ranges are extended due to copy coalescing.
1326 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1327 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1328 VNInfo *VNI = I->first;
1329 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1330 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1331 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1332 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1335 // Update kill info. Some live ranges are extended due to copy coalescing.
1336 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1337 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1338 VNInfo *VNI = I->first;
1339 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1340 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1341 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1342 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1345 // If we get here, we know that we can coalesce the live ranges. Ask the
1346 // intervals to coalesce themselves now.
1347 if ((RHS.ranges.size() > LHS.ranges.size() &&
1348 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1349 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1350 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1353 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1360 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1361 // depth of the basic block (the unsigned), and then on the MBB number.
1362 struct DepthMBBCompare {
1363 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1364 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1365 if (LHS.first > RHS.first) return true; // Deeper loops first
1366 return LHS.first == RHS.first &&
1367 LHS.second->getNumber() < RHS.second->getNumber();
1372 /// getRepIntervalSize - Returns the size of the interval that represents the
1373 /// specified register.
1375 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1376 return Rc->getRepIntervalSize(Reg);
1379 /// CopyRecSort::operator - Join priority queue sorting function.
1381 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1382 // Inner loops first.
1383 if (left.LoopDepth > right.LoopDepth)
1385 else if (left.LoopDepth == right.LoopDepth)
1386 if (left.isBackEdge && !right.isBackEdge)
1391 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1392 std::vector<CopyRec> &TryAgain) {
1393 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1395 std::vector<CopyRec> VirtCopies;
1396 std::vector<CopyRec> PhysCopies;
1397 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1398 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1400 MachineInstr *Inst = MII++;
1402 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1403 unsigned SrcReg, DstReg;
1404 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1405 DstReg = Inst->getOperand(0).getReg();
1406 SrcReg = Inst->getOperand(1).getReg();
1407 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1410 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1411 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1413 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1415 if (SrcIsPhys || DstIsPhys)
1416 PhysCopies.push_back(CopyRec(Inst, 0, false));
1418 VirtCopies.push_back(CopyRec(Inst, 0, false));
1425 // Try coalescing physical register + virtual register first.
1426 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1427 CopyRec &TheCopy = PhysCopies[i];
1429 if (!JoinCopy(TheCopy, Again))
1431 TryAgain.push_back(TheCopy);
1433 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1434 CopyRec &TheCopy = VirtCopies[i];
1436 if (!JoinCopy(TheCopy, Again))
1438 TryAgain.push_back(TheCopy);
1442 void SimpleRegisterCoalescing::joinIntervals() {
1443 DOUT << "********** JOINING INTERVALS ***********\n";
1446 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1448 std::vector<CopyRec> TryAgainList;
1449 if (loopInfo->begin() == loopInfo->end()) {
1450 // If there are no loops in the function, join intervals in function order.
1451 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1453 CopyCoalesceInMBB(I, TryAgainList);
1455 // Otherwise, join intervals in inner loops before other intervals.
1456 // Unfortunately we can't just iterate over loop hierarchy here because
1457 // there may be more MBB's than BB's. Collect MBB's for sorting.
1459 // Join intervals in the function prolog first. We want to join physical
1460 // registers with virtual registers before the intervals got too long.
1461 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1462 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1463 MachineBasicBlock *MBB = I;
1464 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1467 // Sort by loop depth.
1468 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1470 // Finally, join intervals in loop nest order.
1471 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1472 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1475 // Joining intervals can allow other intervals to be joined. Iteratively join
1476 // until we make no progress.
1478 SmallVector<CopyRec, 16> TryAgain;
1479 bool ProgressMade = true;
1480 while (ProgressMade) {
1481 ProgressMade = false;
1482 while (!JoinQueue->empty()) {
1483 CopyRec R = JoinQueue->pop();
1485 bool Success = JoinCopy(R, Again);
1487 ProgressMade = true;
1489 TryAgain.push_back(R);
1493 while (!TryAgain.empty()) {
1494 JoinQueue->push(TryAgain.back());
1495 TryAgain.pop_back();
1500 bool ProgressMade = true;
1501 while (ProgressMade) {
1502 ProgressMade = false;
1504 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1505 CopyRec &TheCopy = TryAgainList[i];
1508 bool Success = JoinCopy(TheCopy, Again);
1509 if (Success || !Again) {
1510 TheCopy.MI = 0; // Mark this one as done.
1511 ProgressMade = true;
1522 /// Return true if the two specified registers belong to different register
1523 /// classes. The registers may be either phys or virt regs.
1524 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1525 unsigned RegB) const {
1527 // Get the register classes for the first reg.
1528 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1529 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1530 "Shouldn't consider two physregs!");
1531 return !mri_->getRegClass(RegB)->contains(RegA);
1534 // Compare against the regclass for the second reg.
1535 const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1536 if (TargetRegisterInfo::isVirtualRegister(RegB))
1537 return RegClass != mri_->getRegClass(RegB);
1539 return !RegClass->contains(RegB);
1542 /// lastRegisterUse - Returns the last use of the specific register between
1543 /// cycles Start and End or NULL if there are no uses.
1545 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1546 unsigned Reg, unsigned &UseIdx) const{
1548 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1549 MachineOperand *LastUse = NULL;
1550 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1551 E = mri_->use_end(); I != E; ++I) {
1552 MachineOperand &Use = I.getOperand();
1553 MachineInstr *UseMI = Use.getParent();
1554 unsigned SrcReg, DstReg;
1555 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1556 // Ignore identity copies.
1558 unsigned Idx = li_->getInstructionIndex(UseMI);
1559 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1567 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1570 // Skip deleted instructions
1571 MachineInstr *MI = li_->getInstructionFromIndex(e);
1572 while ((e - InstrSlots::NUM) >= s && !MI) {
1573 e -= InstrSlots::NUM;
1574 MI = li_->getInstructionFromIndex(e);
1576 if (e < s || MI == NULL)
1579 // Ignore identity copies.
1580 unsigned SrcReg, DstReg;
1581 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1582 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1583 MachineOperand &Use = MI->getOperand(i);
1584 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1585 tri_->regsOverlap(Use.getReg(), Reg)) {
1591 e -= InstrSlots::NUM;
1598 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1599 if (TargetRegisterInfo::isPhysicalRegister(reg))
1600 cerr << tri_->getName(reg);
1602 cerr << "%reg" << reg;
1605 void SimpleRegisterCoalescing::releaseMemory() {
1606 JoinedCopies.clear();
1609 static bool isZeroLengthInterval(LiveInterval *li) {
1610 for (LiveInterval::Ranges::const_iterator
1611 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1612 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1617 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1619 mri_ = &fn.getRegInfo();
1620 tm_ = &fn.getTarget();
1621 tri_ = tm_->getRegisterInfo();
1622 tii_ = tm_->getInstrInfo();
1623 li_ = &getAnalysis<LiveIntervals>();
1624 lv_ = &getAnalysis<LiveVariables>();
1625 loopInfo = &getAnalysis<MachineLoopInfo>();
1627 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1628 << "********** Function: "
1629 << ((Value*)mf_->getFunction())->getName() << '\n';
1631 allocatableRegs_ = tri_->getAllocatableSet(fn);
1632 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1633 E = tri_->regclass_end(); I != E; ++I)
1634 allocatableRCRegs_.insert(std::make_pair(*I,
1635 tri_->getAllocatableSet(fn, *I)));
1637 // Join (coalesce) intervals if requested.
1638 if (EnableJoining) {
1640 DOUT << "********** INTERVALS POST JOINING **********\n";
1641 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1642 I->second.print(DOUT, tri_);
1646 // Delete all coalesced copies.
1647 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1648 E = JoinedCopies.end(); I != E; ++I) {
1649 MachineInstr *CopyMI = *I;
1650 unsigned SrcReg, DstReg;
1651 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg);
1652 if (CopyMI->registerDefIsDead(DstReg)) {
1653 LiveInterval &li = li_->getInterval(DstReg);
1654 ShortenDeadCopySrcLiveRange(li, CopyMI);
1655 ShortenDeadCopyLiveRange(li, CopyMI);
1657 li_->RemoveMachineInstrFromMaps(*I);
1658 (*I)->eraseFromParent();
1663 // Perform a final pass over the instructions and compute spill weights
1664 // and remove identity moves.
1665 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1666 mbbi != mbbe; ++mbbi) {
1667 MachineBasicBlock* mbb = mbbi;
1668 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1670 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1672 // if the move will be an identity move delete it
1673 unsigned srcReg, dstReg;
1674 if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
1675 if (li_->hasInterval(srcReg)) {
1676 LiveInterval &RegInt = li_->getInterval(srcReg);
1677 // If def of this move instruction is dead, remove its live range
1678 // from the dstination register's live interval.
1679 if (mii->registerDefIsDead(dstReg)) {
1680 ShortenDeadCopySrcLiveRange(RegInt, mii);
1681 ShortenDeadCopyLiveRange(RegInt, mii);
1684 li_->RemoveMachineInstrFromMaps(mii);
1685 mii = mbbi->erase(mii);
1688 SmallSet<unsigned, 4> UniqueUses;
1689 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1690 const MachineOperand &mop = mii->getOperand(i);
1691 if (mop.isRegister() && mop.getReg() &&
1692 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1693 unsigned reg = mop.getReg();
1694 // Multiple uses of reg by the same instruction. It should not
1695 // contribute to spill weight again.
1696 if (UniqueUses.count(reg) != 0)
1698 LiveInterval &RegInt = li_->getInterval(reg);
1700 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1701 UniqueUses.insert(reg);
1709 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1710 LiveInterval &LI = I->second;
1711 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1712 // If the live interval length is essentially zero, i.e. in every live
1713 // range the use follows def immediately, it doesn't make sense to spill
1714 // it and hope it will be easier to allocate for this li.
1715 if (isZeroLengthInterval(&LI))
1716 LI.weight = HUGE_VALF;
1718 bool isLoad = false;
1719 if (li_->isReMaterializable(LI, isLoad)) {
1720 // If all of the definitions of the interval are re-materializable,
1721 // it is a preferred candidate for spilling. If non of the defs are
1722 // loads, then it's potentially very cheap to re-materialize.
1723 // FIXME: this gets much more complicated once we support non-trivial
1724 // re-materialization.
1732 // Slightly prefer live interval that has been assigned a preferred reg.
1736 // Divide the weight of the interval by its size. This encourages
1737 // spilling of intervals that are large and have few uses, and
1738 // discourages spilling of small intervals with many uses.
1739 LI.weight /= LI.getSize();
1747 /// print - Implement the dump method.
1748 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1752 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1753 return new SimpleRegisterCoalescing();
1756 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1757 DEFINING_FILE_FOR(SimpleRegisterCoalescing)