1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
37 STATISTIC(numJoins , "Number of interval joins performed");
38 STATISTIC(numSubJoins , "Number of subclass 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;
46 EnableJoining("join-liveintervals",
47 cl::desc("Coalesce copies (default=true)"),
51 NewHeuristic("new-coalescer-heuristic",
52 cl::desc("Use new coalescer heuristic"),
53 cl::init(false), cl::Hidden);
56 CrossClassJoin("join-subclass-copies",
57 cl::desc("Coalesce copies to sub- register class"),
58 cl::init(false), cl::Hidden);
60 static RegisterPass<SimpleRegisterCoalescing>
61 X("simple-register-coalescing", "Simple Register Coalescing");
63 // Declare that we implement the RegisterCoalescer interface
64 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
66 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
68 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addPreserved<LiveIntervals>();
70 AU.addPreserved<MachineLoopInfo>();
71 AU.addPreservedID(MachineDominatorsID);
72 AU.addPreservedID(PHIEliminationID);
73 AU.addPreservedID(TwoAddressInstructionPassID);
74 AU.addRequired<LiveIntervals>();
75 AU.addRequired<MachineLoopInfo>();
76 MachineFunctionPass::getAnalysisUsage(AU);
79 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
80 /// being the source and IntB being the dest, thus this defines a value number
81 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
82 /// see if we can merge these two pieces of B into a single value number,
83 /// eliminating a copy. For example:
87 /// B1 = A3 <- this copy
89 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
90 /// value number to be replaced with B0 (which simplifies the B liveinterval).
92 /// This returns true if an interval was modified.
94 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
96 MachineInstr *CopyMI) {
97 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
99 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
100 // the example above.
101 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
102 if (BLR == IntB.end()) // Should never happen!
104 VNInfo *BValNo = BLR->valno;
106 // Get the location that B is defined at. Two options: either this value has
107 // an unknown definition point or it is defined at CopyIdx. If unknown, we
109 if (!BValNo->copy) return false;
110 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
112 // AValNo is the value number in A that defines the copy, A3 in the example.
113 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
114 if (ALR == IntA.end()) // Should never happen!
116 VNInfo *AValNo = ALR->valno;
118 // If AValNo is defined as a copy from IntB, we can potentially process this.
119 // Get the instruction that defines this value number.
120 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
121 if (!SrcReg) return false; // Not defined by a copy.
123 // If the value number is not defined by a copy instruction, ignore it.
125 // If the source register comes from an interval other than IntB, we can't
127 if (SrcReg != IntB.reg) return false;
129 // Get the LiveRange in IntB that this value number starts with.
130 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
131 if (ValLR == IntB.end()) // Should never happen!
134 // Make sure that the end of the live range is inside the same block as
136 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
138 ValLREndInst->getParent() != CopyMI->getParent()) return false;
140 // Okay, we now know that ValLR ends in the same block that the CopyMI
141 // live-range starts. If there are no intervening live ranges between them in
142 // IntB, we can merge them.
143 if (ValLR+1 != BLR) return false;
145 // If a live interval is a physical register, conservatively check if any
146 // of its sub-registers is overlapping the live interval of the virtual
147 // register. If so, do not coalesce.
148 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
149 *tri_->getSubRegisters(IntB.reg)) {
150 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
151 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
152 DOUT << "Interfere with sub-register ";
153 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
158 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
160 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
161 // We are about to delete CopyMI, so need to remove it as the 'instruction
162 // that defines this value #'. Update the the valnum with the new defining
164 BValNo->def = FillerStart;
167 // Okay, we can merge them. We need to insert a new liverange:
168 // [ValLR.end, BLR.begin) of either value number, then we merge the
169 // two value numbers.
170 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
172 // If the IntB live range is assigned to a physical register, and if that
173 // physreg has aliases,
174 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
175 // Update the liveintervals of sub-registers.
176 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
177 LiveInterval &AliasLI = li_->getInterval(*AS);
178 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
179 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
183 // Okay, merge "B1" into the same value number as "B0".
184 if (BValNo != ValLR->valno)
185 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
186 DOUT << " result = "; IntB.print(DOUT, tri_);
189 // If the source instruction was killing the source register before the
190 // merge, unset the isKill marker given the live range has been extended.
191 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
193 ValLREndInst->getOperand(UIdx).setIsKill(false);
199 /// HasOtherReachingDefs - Return true if there are definitions of IntB
200 /// other than BValNo val# that can reach uses of AValno val# of IntA.
201 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
205 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
207 if (AI->valno != AValNo) continue;
208 LiveInterval::Ranges::iterator BI =
209 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
210 if (BI != IntB.ranges.begin())
212 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
213 if (BI->valno == BValNo)
215 if (BI->start <= AI->start && BI->end > AI->start)
217 if (BI->start > AI->start && BI->start < AI->end)
224 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
225 /// being the source and IntB being the dest, thus this defines a value number
226 /// in IntB. If the source value number (in IntA) is defined by a commutable
227 /// instruction and its other operand is coalesced to the copy dest register,
228 /// see if we can transform the copy into a noop by commuting the definition. For
231 /// A3 = op A2 B0<kill>
233 /// B1 = A3 <- this copy
235 /// = op A3 <- more uses
239 /// B2 = op B0 A2<kill>
241 /// B1 = B2 <- now an identify copy
243 /// = op B2 <- more uses
245 /// This returns true if an interval was modified.
247 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
249 MachineInstr *CopyMI) {
250 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
252 // FIXME: For now, only eliminate the copy by commuting its def when the
253 // source register is a virtual register. We want to guard against cases
254 // where the copy is a back edge copy and commuting the def lengthen the
255 // live interval of the source register to the entire loop.
256 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
259 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
260 // the example above.
261 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
262 if (BLR == IntB.end()) // Should never happen!
264 VNInfo *BValNo = BLR->valno;
266 // Get the location that B is defined at. Two options: either this value has
267 // an unknown definition point or it is defined at CopyIdx. If unknown, we
269 if (!BValNo->copy) return false;
270 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
272 // AValNo is the value number in A that defines the copy, A3 in the example.
273 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
274 if (ALR == IntA.end()) // Should never happen!
276 VNInfo *AValNo = ALR->valno;
277 // If other defs can reach uses of this def, then it's not safe to perform
279 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
281 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
282 const TargetInstrDesc &TID = DefMI->getDesc();
284 if (!TID.isCommutable() ||
285 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
288 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
289 unsigned NewReg = NewDstMO.getReg();
290 if (NewReg != IntB.reg || !NewDstMO.isKill())
293 // Make sure there are no other definitions of IntB that would reach the
294 // uses which the new definition can reach.
295 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
298 // If some of the uses of IntA.reg is already coalesced away, return false.
299 // It's not possible to determine whether it's safe to perform the coalescing.
300 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
301 UE = mri_->use_end(); UI != UE; ++UI) {
302 MachineInstr *UseMI = &*UI;
303 unsigned UseIdx = li_->getInstructionIndex(UseMI);
304 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
305 if (ULR == IntA.end())
307 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
311 // At this point we have decided that it is legal to do this
312 // transformation. Start by commuting the instruction.
313 MachineBasicBlock *MBB = DefMI->getParent();
314 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
317 if (NewMI != DefMI) {
318 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
319 MBB->insert(DefMI, NewMI);
322 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
323 NewMI->getOperand(OpIdx).setIsKill();
325 bool BHasPHIKill = BValNo->hasPHIKill;
326 SmallVector<VNInfo*, 4> BDeadValNos;
327 SmallVector<unsigned, 4> BKills;
328 std::map<unsigned, unsigned> BExtend;
330 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
339 // then do not add kills of A to the newly created B interval.
340 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
342 BExtend[ALR->end] = BLR->end;
344 // Update uses of IntA of the specific Val# with IntB.
345 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
346 UE = mri_->use_end(); UI != UE;) {
347 MachineOperand &UseMO = UI.getOperand();
348 MachineInstr *UseMI = &*UI;
350 if (JoinedCopies.count(UseMI))
352 unsigned UseIdx = li_->getInstructionIndex(UseMI);
353 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
354 if (ULR == IntA.end() || ULR->valno != AValNo)
356 UseMO.setReg(NewReg);
359 if (UseMO.isKill()) {
361 UseMO.setIsKill(false);
363 BKills.push_back(li_->getUseIndex(UseIdx)+1);
365 unsigned SrcReg, DstReg;
366 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
368 if (DstReg == IntB.reg) {
369 // This copy will become a noop. If it's defining a new val#,
370 // remove that val# as well. However this live range is being
371 // extended to the end of the existing live range defined by the copy.
372 unsigned DefIdx = li_->getDefIndex(UseIdx);
373 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
374 BHasPHIKill |= DLR->valno->hasPHIKill;
375 assert(DLR->valno->def == DefIdx);
376 BDeadValNos.push_back(DLR->valno);
377 BExtend[DLR->start] = DLR->end;
378 JoinedCopies.insert(UseMI);
379 // If this is a kill but it's going to be removed, the last use
380 // of the same val# is the new kill.
386 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
387 // simply extend BLR if CopyMI doesn't end the range.
388 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
390 // Remove val#'s defined by copies that will be coalesced away.
391 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
392 IntB.removeValNo(BDeadValNos[i]);
394 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
395 // is updated. Kills are also updated.
396 VNInfo *ValNo = BValNo;
397 ValNo->def = AValNo->def;
399 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
400 unsigned Kill = ValNo->kills[j];
401 if (Kill != BLR->end)
402 BKills.push_back(Kill);
404 ValNo->kills.clear();
405 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
407 if (AI->valno != AValNo) continue;
408 unsigned End = AI->end;
409 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
410 if (EI != BExtend.end())
412 IntB.addRange(LiveRange(AI->start, End, ValNo));
414 IntB.addKills(ValNo, BKills);
415 ValNo->hasPHIKill = BHasPHIKill;
417 DOUT << " result = "; IntB.print(DOUT, tri_);
420 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
421 IntA.removeValNo(AValNo);
422 DOUT << " result = "; IntA.print(DOUT, tri_);
429 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
431 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
432 unsigned DstReg) const {
433 MachineBasicBlock *MBB = CopyMI->getParent();
434 const MachineLoop *L = loopInfo->getLoopFor(MBB);
437 if (MBB != L->getLoopLatch())
440 LiveInterval &LI = li_->getInterval(DstReg);
441 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
442 LiveInterval::const_iterator DstLR =
443 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
444 if (DstLR == LI.end())
446 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
447 if (DstLR->valno->kills.size() == 1 &&
448 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
453 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
454 /// update the subregister number if it is not zero. If DstReg is a
455 /// physical register and the existing subregister number of the def / use
456 /// being updated is not zero, make sure to set it to the correct physical
459 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
461 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
462 if (DstIsPhys && SubIdx) {
463 // Figure out the real physical register we are updating with.
464 DstReg = tri_->getSubReg(DstReg, SubIdx);
468 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
469 E = mri_->reg_end(); I != E; ) {
470 MachineOperand &O = I.getOperand();
471 MachineInstr *UseMI = &*I;
473 unsigned OldSubIdx = O.getSubReg();
475 unsigned UseDstReg = DstReg;
477 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
481 // Sub-register indexes goes from small to large. e.g.
482 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
483 // EAX: 1 -> AL, 2 -> AX
484 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
485 // sub-register 2 is also AX.
486 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
487 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
490 // Remove would-be duplicated kill marker.
491 if (O.isKill() && UseMI->killsRegister(DstReg))
498 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
499 /// registers due to insert_subreg coalescing. e.g.
501 /// r1025 = implicit_def
502 /// r1025 = insert_subreg r1025, r1024
506 /// r1025 = implicit_def
507 /// r1025 = insert_subreg r1025, r1025
510 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
511 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
512 E = mri_->reg_end(); I != E; ) {
513 MachineOperand &O = I.getOperand();
514 MachineInstr *DefMI = &*I;
518 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
520 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
522 li_->RemoveMachineInstrFromMaps(DefMI);
523 DefMI->eraseFromParent();
527 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
528 /// due to live range lengthening as the result of coalescing.
529 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
531 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
532 UE = mri_->use_end(); UI != UE; ++UI) {
533 MachineOperand &UseMO = UI.getOperand();
534 if (UseMO.isKill()) {
535 MachineInstr *UseMI = UseMO.getParent();
538 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
541 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
542 if (JoinedCopies.count(UseMI))
544 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
545 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
546 UseMO.setIsKill(false);
551 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
552 /// from a physical register live interval as well as from the live intervals
553 /// of its sub-registers.
554 static void removeRange(LiveInterval &li, unsigned Start, unsigned 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 unsigned RemoveEnd = Start;
563 while (RemoveEnd != End) {
564 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
567 RemoveEnd = (LR->end < End) ? LR->end : End;
568 sli.removeRange(Start, RemoveEnd, true);
575 /// removeIntervalIfEmpty - Check if the live interval of a physical register
576 /// is empty, if so remove it and also remove the empty intervals of its
577 /// sub-registers. Return true if live interval is removed.
578 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
579 const TargetRegisterInfo *tri_) {
581 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
582 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
583 if (!li_->hasInterval(*SR))
585 LiveInterval &sli = li_->getInterval(*SR);
587 li_->removeInterval(*SR);
589 li_->removeInterval(li.reg);
595 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
596 /// Return true if live interval is removed.
597 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
598 MachineInstr *CopyMI) {
599 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
600 LiveInterval::iterator MLR =
601 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
603 return false; // Already removed by ShortenDeadCopySrcLiveRange.
604 unsigned RemoveStart = MLR->start;
605 unsigned RemoveEnd = MLR->end;
606 // Remove the liverange that's defined by this.
607 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
608 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
609 return removeIntervalIfEmpty(li, li_, tri_);
614 /// PropagateDeadness - Propagate the dead marker to the instruction which
615 /// defines the val#.
616 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
617 unsigned &LRStart, LiveIntervals *li_,
618 const TargetRegisterInfo* tri_) {
619 MachineInstr *DefMI =
620 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
621 if (DefMI && DefMI != CopyMI) {
622 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
624 DefMI->getOperand(DeadIdx).setIsDead();
625 // A dead def should have a single cycle interval.
631 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
632 /// fallthoughs to SuccMBB.
633 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
634 MachineBasicBlock *SuccMBB,
635 const TargetInstrInfo *tii_) {
638 MachineBasicBlock *TBB = 0, *FBB = 0;
639 std::vector<MachineOperand> Cond;
640 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
641 MBB->isSuccessor(SuccMBB);
644 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
645 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
646 /// ends the live range there. If there isn't another use, then this live range
647 /// is dead. Return true if live interval is removed.
649 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
650 MachineInstr *CopyMI) {
651 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
653 // FIXME: special case: function live in. It can be a general case if the
654 // first instruction index starts at > 0 value.
655 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
656 // Live-in to the function but dead. Remove it from entry live-in set.
657 if (mf_->begin()->isLiveIn(li.reg))
658 mf_->begin()->removeLiveIn(li.reg);
659 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
660 removeRange(li, LR->start, LR->end, li_, tri_);
661 return removeIntervalIfEmpty(li, li_, tri_);
664 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
666 // Livein but defined by a phi.
669 unsigned RemoveStart = LR->start;
670 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
671 if (LR->end > RemoveEnd)
672 // More uses past this copy? Nothing to do.
675 MachineBasicBlock *CopyMBB = CopyMI->getParent();
676 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
678 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
681 MachineInstr *LastUseMI = LastUse->getParent();
682 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
689 // r1025<dead> = r1024<kill>
690 if (MBBStart < LR->end)
691 removeRange(li, MBBStart, LR->end, li_, tri_);
695 // There are uses before the copy, just shorten the live range to the end
697 LastUse->setIsKill();
698 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
699 unsigned SrcReg, DstReg;
700 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
702 // Last use is itself an identity code.
703 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
704 LastUseMI->getOperand(DeadIdx).setIsDead();
710 if (LR->start <= MBBStart && LR->end > MBBStart) {
711 if (LR->start == 0) {
712 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
713 // Live-in to the function but dead. Remove it from entry live-in set.
714 mf_->begin()->removeLiveIn(li.reg);
716 // FIXME: Shorten intervals in BBs that reaches this BB.
719 if (LR->valno->def == RemoveStart)
720 // If the def MI defines the val#, propagate the dead marker.
721 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
723 removeRange(li, RemoveStart, LR->end, li_, tri_);
724 return removeIntervalIfEmpty(li, li_, tri_);
727 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
728 /// from an implicit def to another register can be coalesced away.
729 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
731 LiveInterval &ImpLi) const{
732 if (!CopyMI->killsRegister(ImpLi.reg))
734 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
735 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
738 if (LR->valno->hasPHIKill)
740 if (LR->valno->def != CopyIdx)
742 // Make sure all of val# uses are copies.
743 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
744 UE = mri_->use_end(); UI != UE;) {
745 MachineInstr *UseMI = &*UI;
747 if (JoinedCopies.count(UseMI))
749 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
750 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
751 if (ULR == li.end() || ULR->valno != LR->valno)
753 // If the use is not a use, then it's not safe to coalesce the move.
754 unsigned SrcReg, DstReg;
755 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
756 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
757 UseMI->getOperand(1).getReg() == li.reg)
766 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
767 /// def and it is being removed. Turn all copies from this value# into
768 /// identity copies so they will be removed.
769 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
771 SmallVector<MachineInstr*, 4> ImpDefs;
772 MachineOperand *LastUse = NULL;
773 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
774 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
775 RE = mri_->reg_end(); RI != RE;) {
776 MachineOperand *MO = &RI.getOperand();
777 MachineInstr *MI = &*RI;
780 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
781 ImpDefs.push_back(MI);
785 if (JoinedCopies.count(MI))
787 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
788 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
789 if (ULR == li.end() || ULR->valno != VNI)
791 // If the use is a copy, turn it into an identity copy.
792 unsigned SrcReg, DstReg;
793 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
794 // Each use MI may have multiple uses of this register. Change them all.
795 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
796 MachineOperand &MO = MI->getOperand(i);
797 if (MO.isReg() && MO.getReg() == li.reg)
800 JoinedCopies.insert(MI);
801 } else if (UseIdx > LastUseIdx) {
807 LastUse->setIsKill();
809 // Remove dead implicit_def's.
810 while (!ImpDefs.empty()) {
811 MachineInstr *ImpDef = ImpDefs.back();
813 li_->RemoveMachineInstrFromMaps(ImpDef);
814 ImpDef->eraseFromParent();
819 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
820 const TargetRegisterClass *RC,
821 const TargetRegisterInfo* TRI) {
822 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
823 unsigned SR = *SRs; ++SRs)
824 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
829 /// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
830 /// a subset of the register class of SrcReg, return true if it's profitable
831 /// to coalesce the two registers.
833 SimpleRegisterCoalescing::isProfitableToCoalesceToSubRC(unsigned SrcReg,
835 MachineBasicBlock *MBB){
839 // First let's make sure all uses are in the same MBB.
840 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
841 RE = mri_->reg_end(); RI != RE; ++RI) {
842 MachineInstr &MI = *RI;
843 if (MI.getParent() != MBB)
846 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(DstReg),
847 RE = mri_->reg_end(); RI != RE; ++RI) {
848 MachineInstr &MI = *RI;
849 if (MI.getParent() != MBB)
853 // Then make sure the intervals are *short*.
854 LiveInterval &SrcInt = li_->getInterval(SrcReg);
855 LiveInterval &DstInt = li_->getInterval(DstReg);
856 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
857 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
858 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
859 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
860 return (SrcSize + DstSize) <= Threshold;
864 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
865 /// which are the src/dst of the copy instruction CopyMI. This returns true
866 /// if the copy was successfully coalesced away. If it is not currently
867 /// possible to coalesce this interval, but it may be possible if other
868 /// things get coalesced, then it returns true by reference in 'Again'.
869 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
870 MachineInstr *CopyMI = TheCopy.MI;
873 if (JoinedCopies.count(CopyMI))
874 return false; // Already done.
876 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
880 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
881 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
884 DstReg = CopyMI->getOperand(0).getReg();
885 SrcReg = CopyMI->getOperand(1).getReg();
886 } else if (isInsSubReg) {
887 if (CopyMI->getOperand(2).getSubReg()) {
888 DOUT << "\tSource of insert_subreg is already coalesced "
889 << "to another register.\n";
890 return false; // Not coalescable.
892 DstReg = CopyMI->getOperand(0).getReg();
893 SrcReg = CopyMI->getOperand(2).getReg();
894 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
895 assert(0 && "Unrecognized copy instruction!");
899 // If they are already joined we continue.
900 if (SrcReg == DstReg) {
901 DOUT << "\tCopy already coalesced.\n";
902 return false; // Not coalescable.
905 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
906 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
908 // If they are both physical registers, we cannot join them.
909 if (SrcIsPhys && DstIsPhys) {
910 DOUT << "\tCan not coalesce physregs.\n";
911 return false; // Not coalescable.
914 // We only join virtual registers with allocatable physical registers.
915 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
916 DOUT << "\tSrc reg is unallocatable physreg.\n";
917 return false; // Not coalescable.
919 if (DstIsPhys && !allocatableRegs_[DstReg]) {
920 DOUT << "\tDst reg is unallocatable physreg.\n";
921 return false; // Not coalescable.
924 // Should be non-null only when coalescing to a sub-register class.
925 const TargetRegisterClass *SubRC = NULL;
926 MachineBasicBlock *CopyMBB = CopyMI->getParent();
927 unsigned RealDstReg = 0;
928 unsigned RealSrcReg = 0;
929 if (isExtSubReg || isInsSubReg) {
930 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
931 if (SrcIsPhys && isExtSubReg) {
932 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
933 // coalesced with AX.
934 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
936 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
937 // coalesced to a larger register so the subreg indices cancel out.
938 if (DstSubIdx != SubIdx) {
939 DOUT << "\t Sub-register indices mismatch.\n";
940 return false; // Not coalescable.
943 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
945 } else if (DstIsPhys && isInsSubReg) {
946 // EAX = INSERT_SUBREG EAX, r1024, 0
947 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
949 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
950 // coalesced to a larger register so the subreg indices cancel out.
951 if (SrcSubIdx != SubIdx) {
952 DOUT << "\t Sub-register indices mismatch.\n";
953 return false; // Not coalescable.
956 DstReg = tri_->getSubReg(DstReg, SubIdx);
958 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
959 // If this is a extract_subreg where dst is a physical register, e.g.
960 // cl = EXTRACT_SUBREG reg1024, 1
961 // then create and update the actual physical register allocated to RHS.
963 // reg1024 = INSERT_SUBREG r1024, cl, 1
964 if (CopyMI->getOperand(1).getSubReg()) {
965 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
966 << " of a super-class.\n";
967 return false; // Not coalescable.
969 const TargetRegisterClass *RC =
970 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
972 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
973 assert(RealDstReg && "Invalid extra_subreg instruction!");
975 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
976 assert(RealSrcReg && "Invalid extra_subreg instruction!");
979 // For this type of EXTRACT_SUBREG, conservatively
980 // check if the live interval of the source register interfere with the
981 // actual super physical register we are trying to coalesce with.
982 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
983 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
984 if (li_->hasInterval(PhysReg) &&
985 RHS.overlaps(li_->getInterval(PhysReg))) {
986 DOUT << "Interfere with register ";
987 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
988 return false; // Not coalescable
990 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
991 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
992 DOUT << "Interfere with sub-register ";
993 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
994 return false; // Not coalescable
998 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
999 : CopyMI->getOperand(2).getSubReg();
1001 if (OldSubIdx == SubIdx &&
1002 !differingRegisterClasses(SrcReg, DstReg, SubRC))
1003 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1004 // coalesced to a larger register so the subreg indices cancel out.
1005 // Also check if the other larger register is of the same register
1006 // class as the would be resulting register.
1009 DOUT << "\t Sub-register indices mismatch.\n";
1010 return false; // Not coalescable.
1014 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1015 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1016 unsigned LargeRegSize =
1017 li_->getApproximateInstructionCount(li_->getInterval(LargeReg));
1018 unsigned SmallRegSize =
1019 li_->getApproximateInstructionCount(li_->getInterval(SmallReg));
1020 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
1021 unsigned Threshold = allocatableRCRegs_[RC].count();
1022 // Be conservative. If both sides are virtual registers, do not coalesce
1023 // if this will cause a high use density interval to target a smaller
1024 // set of registers.
1025 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
1026 if ((float)std::distance(mri_->use_begin(SmallReg),
1027 mri_->use_end()) / SmallRegSize <
1028 (float)std::distance(mri_->use_begin(LargeReg),
1029 mri_->use_end()) / LargeRegSize) {
1030 Again = true; // May be possible to coalesce later.
1036 } else if (differingRegisterClasses(SrcReg, DstReg, SubRC)) {
1037 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
1038 // with another? If it's the resulting destination register, then
1039 // the subidx must be propagated to uses (but only those defined
1040 // by the EXTRACT_SUBREG). If it's being coalesced into another
1041 // register, it should be safe because register is assumed to have
1042 // the register class of the super-register.
1044 if (!SubRC || !isProfitableToCoalesceToSubRC(SrcReg, DstReg, CopyMBB)) {
1045 // If they are not of the same register class, we cannot join them.
1046 DOUT << "\tSrc/Dest are different register classes.\n";
1047 // Allow the coalescer to try again in case either side gets coalesced to
1048 // a physical register that's compatible with the other side. e.g.
1049 // r1024 = MOV32to32_ r1025
1050 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1051 Again = true; // May be possible to coalesce later.
1056 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1057 LiveInterval &DstInt = li_->getInterval(DstReg);
1058 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1059 "Register mapping is horribly broken!");
1061 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1062 DOUT << " and "; DstInt.print(DOUT, tri_);
1065 // Check if it is necessary to propagate "isDead" property.
1066 if (!isExtSubReg && !isInsSubReg) {
1067 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1068 bool isDead = mopd->isDead();
1070 // We need to be careful about coalescing a source physical register with a
1071 // virtual register. Once the coalescing is done, it cannot be broken and
1072 // these are not spillable! If the destination interval uses are far away,
1073 // think twice about coalescing them!
1074 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1075 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1076 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1077 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1078 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1079 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1080 if (TheCopy.isBackEdge)
1081 Threshold *= 2; // Favors back edge copies.
1083 // If the virtual register live interval is long but it has low use desity,
1084 // do not join them, instead mark the physical register as its allocation
1086 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1087 if (Length > Threshold &&
1088 (((float)std::distance(mri_->use_begin(JoinVReg),
1089 mri_->use_end()) / Length) < (1.0 / Threshold))) {
1090 JoinVInt.preference = JoinPReg;
1092 DOUT << "\tMay tie down a physical register, abort!\n";
1093 Again = true; // May be possible to coalesce later.
1099 // Okay, attempt to join these two intervals. On failure, this returns false.
1100 // Otherwise, if one of the intervals being joined is a physreg, this method
1101 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1102 // been modified, so we can use this information below to update aliases.
1103 bool Swapped = false;
1104 // If SrcInt is implicitly defined, it's safe to coalesce.
1105 bool isEmpty = SrcInt.empty();
1106 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1107 // Only coalesce an empty interval (defined by implicit_def) with
1108 // another interval which has a valno defined by the CopyMI and the CopyMI
1109 // is a kill of the implicit def.
1110 DOUT << "Not profitable!\n";
1114 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1115 // Coalescing failed.
1117 // If we can eliminate the copy without merging the live ranges, do so now.
1118 if (!isExtSubReg && !isInsSubReg &&
1119 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1120 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1121 JoinedCopies.insert(CopyMI);
1125 // Otherwise, we are unable to join the intervals.
1126 DOUT << "Interference!\n";
1127 Again = true; // May be possible to coalesce later.
1131 LiveInterval *ResSrcInt = &SrcInt;
1132 LiveInterval *ResDstInt = &DstInt;
1134 std::swap(SrcReg, DstReg);
1135 std::swap(ResSrcInt, ResDstInt);
1137 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1138 "LiveInterval::join didn't work right!");
1140 // If we're about to merge live ranges into a physical register live range,
1141 // we have to update any aliased register's live ranges to indicate that they
1142 // have clobbered values for this range.
1143 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1144 // If this is a extract_subreg where dst is a physical register, e.g.
1145 // cl = EXTRACT_SUBREG reg1024, 1
1146 // then create and update the actual physical register allocated to RHS.
1147 if (RealDstReg || RealSrcReg) {
1148 LiveInterval &RealInt =
1149 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1150 SmallSet<const VNInfo*, 4> CopiedValNos;
1151 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1152 E = ResSrcInt->ranges.end(); I != E; ++I) {
1153 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1154 assert(DstLR && "Invalid joined interval!");
1155 const VNInfo *DstValNo = DstLR->valno;
1156 if (CopiedValNos.insert(DstValNo)) {
1157 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1158 li_->getVNInfoAllocator());
1159 ValNo->hasPHIKill = DstValNo->hasPHIKill;
1160 RealInt.addKills(ValNo, DstValNo->kills);
1161 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1165 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1168 // Update the liveintervals of sub-registers.
1169 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1170 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1171 li_->getVNInfoAllocator());
1174 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1175 // larger super-register.
1176 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1177 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1178 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1179 std::swap(SrcReg, DstReg);
1180 std::swap(ResSrcInt, ResDstInt);
1184 // Coalescing to a virtual register that is of a sub-register class of the
1185 // other. Make sure the resulting register is set to the right register class.
1187 mri_->setRegClass(DstReg, SubRC);
1192 // Add all copies that define val# in the source interval into the queue.
1193 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1194 e = ResSrcInt->vni_end(); i != e; ++i) {
1195 const VNInfo *vni = *i;
1196 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1198 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1199 unsigned NewSrcReg, NewDstReg;
1201 JoinedCopies.count(CopyMI) == 0 &&
1202 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1203 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1204 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1205 isBackEdgeCopy(CopyMI, DstReg)));
1210 // Remember to delete the copy instruction.
1211 JoinedCopies.insert(CopyMI);
1213 // Some live range has been lengthened due to colaescing, eliminate the
1214 // unnecessary kills.
1215 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1216 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1217 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1219 // SrcReg is guarateed to be the register whose live interval that is
1221 li_->removeInterval(SrcReg);
1225 // r1024 = implicit_def
1228 RemoveDeadImpDef(DstReg, *ResDstInt);
1229 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1232 // Now the copy is being coalesced away, the val# previously defined
1233 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1234 // length interval. Remove the val#.
1235 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1236 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1237 VNInfo *ImpVal = LR->valno;
1238 assert(ImpVal->def == CopyIdx);
1239 unsigned NextDef = LR->end;
1240 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1241 ResDstInt->removeValNo(ImpVal);
1242 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1243 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1244 // Special case: vr1024 = implicit_def
1245 // vr1024 = insert_subreg vr1024, vr1025, c
1246 // The insert_subreg becomes a "copy" that defines a val# which can itself
1247 // be coalesced away.
1248 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1249 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1250 LR->valno->copy = DefMI;
1254 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1261 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1262 /// compute what the resultant value numbers for each value in the input two
1263 /// ranges will be. This is complicated by copies between the two which can
1264 /// and will commonly cause multiple value numbers to be merged into one.
1266 /// VN is the value number that we're trying to resolve. InstDefiningValue
1267 /// keeps track of the new InstDefiningValue assignment for the result
1268 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1269 /// whether a value in this or other is a copy from the opposite set.
1270 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1271 /// already been assigned.
1273 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1274 /// contains the value number the copy is from.
1276 static unsigned ComputeUltimateVN(VNInfo *VNI,
1277 SmallVector<VNInfo*, 16> &NewVNInfo,
1278 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1279 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1280 SmallVector<int, 16> &ThisValNoAssignments,
1281 SmallVector<int, 16> &OtherValNoAssignments) {
1282 unsigned VN = VNI->id;
1284 // If the VN has already been computed, just return it.
1285 if (ThisValNoAssignments[VN] >= 0)
1286 return ThisValNoAssignments[VN];
1287 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1289 // If this val is not a copy from the other val, then it must be a new value
1290 // number in the destination.
1291 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1292 if (I == ThisFromOther.end()) {
1293 NewVNInfo.push_back(VNI);
1294 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1296 VNInfo *OtherValNo = I->second;
1298 // Otherwise, this *is* a copy from the RHS. If the other side has already
1299 // been computed, return it.
1300 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1301 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1303 // Mark this value number as currently being computed, then ask what the
1304 // ultimate value # of the other value is.
1305 ThisValNoAssignments[VN] = -2;
1306 unsigned UltimateVN =
1307 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1308 OtherValNoAssignments, ThisValNoAssignments);
1309 return ThisValNoAssignments[VN] = UltimateVN;
1312 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1313 return std::find(V.begin(), V.end(), Val) != V.end();
1316 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1317 /// the specified live interval is defined by a copy from the specified
1319 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1322 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1325 if (LR->valno->def == ~0U &&
1326 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1327 *tri_->getSuperRegisters(li.reg)) {
1328 // It's a sub-register live interval, we may not have precise information.
1330 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1331 unsigned SrcReg, DstReg;
1332 if (DefMI && tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1333 DstReg == li.reg && SrcReg == Reg) {
1334 // Cache computed info.
1335 LR->valno->def = LR->start;
1336 LR->valno->copy = DefMI;
1343 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1344 /// caller of this method must guarantee that the RHS only contains a single
1345 /// value number and that the RHS is not defined by a copy from this
1346 /// interval. This returns false if the intervals are not joinable, or it
1347 /// joins them and returns true.
1348 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1349 assert(RHS.containsOneValue());
1351 // Some number (potentially more than one) value numbers in the current
1352 // interval may be defined as copies from the RHS. Scan the overlapping
1353 // portions of the LHS and RHS, keeping track of this and looking for
1354 // overlapping live ranges that are NOT defined as copies. If these exist, we
1357 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1358 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1360 if (LHSIt->start < RHSIt->start) {
1361 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1362 if (LHSIt != LHS.begin()) --LHSIt;
1363 } else if (RHSIt->start < LHSIt->start) {
1364 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1365 if (RHSIt != RHS.begin()) --RHSIt;
1368 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1371 // Determine if these live intervals overlap.
1372 bool Overlaps = false;
1373 if (LHSIt->start <= RHSIt->start)
1374 Overlaps = LHSIt->end > RHSIt->start;
1376 Overlaps = RHSIt->end > LHSIt->start;
1378 // If the live intervals overlap, there are two interesting cases: if the
1379 // LHS interval is defined by a copy from the RHS, it's ok and we record
1380 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1381 // coalesce these live ranges and we bail out.
1383 // If we haven't already recorded that this value # is safe, check it.
1384 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1385 // Copy from the RHS?
1386 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1387 return false; // Nope, bail out.
1389 if (LHSIt->contains(RHSIt->valno->def))
1390 // Here is an interesting situation:
1392 // vr1025 = copy vr1024
1397 // Even though vr1025 is copied from vr1024, it's not safe to
1398 // coalesced them since live range of vr1025 intersects the
1399 // def of vr1024. This happens because vr1025 is assigned the
1400 // value of the previous iteration of vr1024.
1402 EliminatedLHSVals.push_back(LHSIt->valno);
1405 // We know this entire LHS live range is okay, so skip it now.
1406 if (++LHSIt == LHSEnd) break;
1410 if (LHSIt->end < RHSIt->end) {
1411 if (++LHSIt == LHSEnd) break;
1413 // One interesting case to check here. It's possible that we have
1414 // something like "X3 = Y" which defines a new value number in the LHS,
1415 // and is the last use of this liverange of the RHS. In this case, we
1416 // want to notice this copy (so that it gets coalesced away) even though
1417 // the live ranges don't actually overlap.
1418 if (LHSIt->start == RHSIt->end) {
1419 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1420 // We already know that this value number is going to be merged in
1421 // if coalescing succeeds. Just skip the liverange.
1422 if (++LHSIt == LHSEnd) break;
1424 // Otherwise, if this is a copy from the RHS, mark it as being merged
1426 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1427 if (LHSIt->contains(RHSIt->valno->def))
1428 // Here is an interesting situation:
1430 // vr1025 = copy vr1024
1435 // Even though vr1025 is copied from vr1024, it's not safe to
1436 // coalesced them since live range of vr1025 intersects the
1437 // def of vr1024. This happens because vr1025 is assigned the
1438 // value of the previous iteration of vr1024.
1440 EliminatedLHSVals.push_back(LHSIt->valno);
1442 // We know this entire LHS live range is okay, so skip it now.
1443 if (++LHSIt == LHSEnd) break;
1448 if (++RHSIt == RHSEnd) break;
1452 // If we got here, we know that the coalescing will be successful and that
1453 // the value numbers in EliminatedLHSVals will all be merged together. Since
1454 // the most common case is that EliminatedLHSVals has a single number, we
1455 // optimize for it: if there is more than one value, we merge them all into
1456 // the lowest numbered one, then handle the interval as if we were merging
1457 // with one value number.
1459 if (EliminatedLHSVals.size() > 1) {
1460 // Loop through all the equal value numbers merging them into the smallest
1462 VNInfo *Smallest = EliminatedLHSVals[0];
1463 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1464 if (EliminatedLHSVals[i]->id < Smallest->id) {
1465 // Merge the current notion of the smallest into the smaller one.
1466 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1467 Smallest = EliminatedLHSVals[i];
1469 // Merge into the smallest.
1470 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1473 LHSValNo = Smallest;
1474 } else if (EliminatedLHSVals.empty()) {
1475 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1476 *tri_->getSuperRegisters(LHS.reg))
1477 // Imprecise sub-register information. Can't handle it.
1479 assert(0 && "No copies from the RHS?");
1481 LHSValNo = EliminatedLHSVals[0];
1484 // Okay, now that there is a single LHS value number that we're merging the
1485 // RHS into, update the value number info for the LHS to indicate that the
1486 // value number is defined where the RHS value number was.
1487 const VNInfo *VNI = RHS.getValNumInfo(0);
1488 LHSValNo->def = VNI->def;
1489 LHSValNo->copy = VNI->copy;
1491 // Okay, the final step is to loop over the RHS live intervals, adding them to
1493 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1494 LHS.addKills(LHSValNo, VNI->kills);
1495 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1496 LHS.weight += RHS.weight;
1497 if (RHS.preference && !LHS.preference)
1498 LHS.preference = RHS.preference;
1503 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1504 /// returns false. Otherwise, if one of the intervals being joined is a
1505 /// physreg, this method always canonicalizes LHS to be it. The output
1506 /// "RHS" will not have been modified, so we can use this information
1507 /// below to update aliases.
1508 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1509 LiveInterval &RHS, bool &Swapped) {
1510 // Compute the final value assignment, assuming that the live ranges can be
1512 SmallVector<int, 16> LHSValNoAssignments;
1513 SmallVector<int, 16> RHSValNoAssignments;
1514 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1515 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1516 SmallVector<VNInfo*, 16> NewVNInfo;
1518 // If a live interval is a physical register, conservatively check if any
1519 // of its sub-registers is overlapping the live interval of the virtual
1520 // register. If so, do not coalesce.
1521 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1522 *tri_->getSubRegisters(LHS.reg)) {
1523 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1524 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1525 DOUT << "Interfere with sub-register ";
1526 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1529 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1530 *tri_->getSubRegisters(RHS.reg)) {
1531 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1532 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1533 DOUT << "Interfere with sub-register ";
1534 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1539 // Compute ultimate value numbers for the LHS and RHS values.
1540 if (RHS.containsOneValue()) {
1541 // Copies from a liveinterval with a single value are simple to handle and
1542 // very common, handle the special case here. This is important, because
1543 // often RHS is small and LHS is large (e.g. a physreg).
1545 // Find out if the RHS is defined as a copy from some value in the LHS.
1546 int RHSVal0DefinedFromLHS = -1;
1548 VNInfo *RHSValNoInfo = NULL;
1549 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1550 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1551 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1552 // If RHS is not defined as a copy from the LHS, we can use simpler and
1553 // faster checks to see if the live ranges are coalescable. This joiner
1554 // can't swap the LHS/RHS intervals though.
1555 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1556 return SimpleJoin(LHS, RHS);
1558 RHSValNoInfo = RHSValNoInfo0;
1561 // It was defined as a copy from the LHS, find out what value # it is.
1562 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1563 RHSValID = RHSValNoInfo->id;
1564 RHSVal0DefinedFromLHS = RHSValID;
1567 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1568 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1569 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1571 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1572 // should now get updated.
1573 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1576 unsigned VN = VNI->id;
1577 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1578 if (LHSSrcReg != RHS.reg) {
1579 // If this is not a copy from the RHS, its value number will be
1580 // unmodified by the coalescing.
1581 NewVNInfo[VN] = VNI;
1582 LHSValNoAssignments[VN] = VN;
1583 } else if (RHSValID == -1) {
1584 // Otherwise, it is a copy from the RHS, and we don't already have a
1585 // value# for it. Keep the current value number, but remember it.
1586 LHSValNoAssignments[VN] = RHSValID = VN;
1587 NewVNInfo[VN] = RHSValNoInfo;
1588 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1590 // Otherwise, use the specified value #.
1591 LHSValNoAssignments[VN] = RHSValID;
1592 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1593 NewVNInfo[VN] = RHSValNoInfo;
1594 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1598 NewVNInfo[VN] = VNI;
1599 LHSValNoAssignments[VN] = VN;
1603 assert(RHSValID != -1 && "Didn't find value #?");
1604 RHSValNoAssignments[0] = RHSValID;
1605 if (RHSVal0DefinedFromLHS != -1) {
1606 // This path doesn't go through ComputeUltimateVN so just set
1608 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1611 // Loop over the value numbers of the LHS, seeing if any are defined from
1613 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1616 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1619 // DstReg is known to be a register in the LHS interval. If the src is
1620 // from the RHS interval, we can use its value #.
1621 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1624 // Figure out the value # from the RHS.
1625 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1628 // Loop over the value numbers of the RHS, seeing if any are defined from
1630 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1633 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1636 // DstReg is known to be a register in the RHS interval. If the src is
1637 // from the LHS interval, we can use its value #.
1638 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1641 // Figure out the value # from the LHS.
1642 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1645 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1646 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1647 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1649 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1652 unsigned VN = VNI->id;
1653 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1655 ComputeUltimateVN(VNI, NewVNInfo,
1656 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1657 LHSValNoAssignments, RHSValNoAssignments);
1659 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1662 unsigned VN = VNI->id;
1663 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1665 // If this value number isn't a copy from the LHS, it's a new number.
1666 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1667 NewVNInfo.push_back(VNI);
1668 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1672 ComputeUltimateVN(VNI, NewVNInfo,
1673 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1674 RHSValNoAssignments, LHSValNoAssignments);
1678 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1679 // interval lists to see if these intervals are coalescable.
1680 LiveInterval::const_iterator I = LHS.begin();
1681 LiveInterval::const_iterator IE = LHS.end();
1682 LiveInterval::const_iterator J = RHS.begin();
1683 LiveInterval::const_iterator JE = RHS.end();
1685 // Skip ahead until the first place of potential sharing.
1686 if (I->start < J->start) {
1687 I = std::upper_bound(I, IE, J->start);
1688 if (I != LHS.begin()) --I;
1689 } else if (J->start < I->start) {
1690 J = std::upper_bound(J, JE, I->start);
1691 if (J != RHS.begin()) --J;
1695 // Determine if these two live ranges overlap.
1697 if (I->start < J->start) {
1698 Overlaps = I->end > J->start;
1700 Overlaps = J->end > I->start;
1703 // If so, check value # info to determine if they are really different.
1705 // If the live range overlap will map to the same value number in the
1706 // result liverange, we can still coalesce them. If not, we can't.
1707 if (LHSValNoAssignments[I->valno->id] !=
1708 RHSValNoAssignments[J->valno->id])
1712 if (I->end < J->end) {
1721 // Update kill info. Some live ranges are extended due to copy coalescing.
1722 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1723 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1724 VNInfo *VNI = I->first;
1725 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1726 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1727 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1728 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1731 // Update kill info. Some live ranges are extended due to copy coalescing.
1732 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1733 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1734 VNInfo *VNI = I->first;
1735 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1736 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1737 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1738 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1741 // If we get here, we know that we can coalesce the live ranges. Ask the
1742 // intervals to coalesce themselves now.
1743 if ((RHS.ranges.size() > LHS.ranges.size() &&
1744 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1745 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1746 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1749 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1756 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1757 // depth of the basic block (the unsigned), and then on the MBB number.
1758 struct DepthMBBCompare {
1759 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1760 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1761 if (LHS.first > RHS.first) return true; // Deeper loops first
1762 return LHS.first == RHS.first &&
1763 LHS.second->getNumber() < RHS.second->getNumber();
1768 /// getRepIntervalSize - Returns the size of the interval that represents the
1769 /// specified register.
1771 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1772 return Rc->getRepIntervalSize(Reg);
1775 /// CopyRecSort::operator - Join priority queue sorting function.
1777 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1778 // Inner loops first.
1779 if (left.LoopDepth > right.LoopDepth)
1781 else if (left.LoopDepth == right.LoopDepth)
1782 if (left.isBackEdge && !right.isBackEdge)
1787 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1788 std::vector<CopyRec> &TryAgain) {
1789 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1791 std::vector<CopyRec> VirtCopies;
1792 std::vector<CopyRec> PhysCopies;
1793 std::vector<CopyRec> ImpDefCopies;
1794 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1795 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1797 MachineInstr *Inst = MII++;
1799 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1800 unsigned SrcReg, DstReg;
1801 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1802 DstReg = Inst->getOperand(0).getReg();
1803 SrcReg = Inst->getOperand(1).getReg();
1804 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1805 DstReg = Inst->getOperand(0).getReg();
1806 SrcReg = Inst->getOperand(2).getReg();
1807 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1810 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1811 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1813 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1815 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1816 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1817 else if (SrcIsPhys || DstIsPhys)
1818 PhysCopies.push_back(CopyRec(Inst, 0, false));
1820 VirtCopies.push_back(CopyRec(Inst, 0, false));
1827 // Try coalescing implicit copies first, followed by copies to / from
1828 // physical registers, then finally copies from virtual registers to
1829 // virtual registers.
1830 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1831 CopyRec &TheCopy = ImpDefCopies[i];
1833 if (!JoinCopy(TheCopy, Again))
1835 TryAgain.push_back(TheCopy);
1837 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1838 CopyRec &TheCopy = PhysCopies[i];
1840 if (!JoinCopy(TheCopy, Again))
1842 TryAgain.push_back(TheCopy);
1844 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1845 CopyRec &TheCopy = VirtCopies[i];
1847 if (!JoinCopy(TheCopy, Again))
1849 TryAgain.push_back(TheCopy);
1853 void SimpleRegisterCoalescing::joinIntervals() {
1854 DOUT << "********** JOINING INTERVALS ***********\n";
1857 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1859 std::vector<CopyRec> TryAgainList;
1860 if (loopInfo->begin() == loopInfo->end()) {
1861 // If there are no loops in the function, join intervals in function order.
1862 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1864 CopyCoalesceInMBB(I, TryAgainList);
1866 // Otherwise, join intervals in inner loops before other intervals.
1867 // Unfortunately we can't just iterate over loop hierarchy here because
1868 // there may be more MBB's than BB's. Collect MBB's for sorting.
1870 // Join intervals in the function prolog first. We want to join physical
1871 // registers with virtual registers before the intervals got too long.
1872 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1873 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1874 MachineBasicBlock *MBB = I;
1875 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1878 // Sort by loop depth.
1879 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1881 // Finally, join intervals in loop nest order.
1882 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1883 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1886 // Joining intervals can allow other intervals to be joined. Iteratively join
1887 // until we make no progress.
1889 SmallVector<CopyRec, 16> TryAgain;
1890 bool ProgressMade = true;
1891 while (ProgressMade) {
1892 ProgressMade = false;
1893 while (!JoinQueue->empty()) {
1894 CopyRec R = JoinQueue->pop();
1896 bool Success = JoinCopy(R, Again);
1898 ProgressMade = true;
1900 TryAgain.push_back(R);
1904 while (!TryAgain.empty()) {
1905 JoinQueue->push(TryAgain.back());
1906 TryAgain.pop_back();
1911 bool ProgressMade = true;
1912 while (ProgressMade) {
1913 ProgressMade = false;
1915 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1916 CopyRec &TheCopy = TryAgainList[i];
1919 bool Success = JoinCopy(TheCopy, Again);
1920 if (Success || !Again) {
1921 TheCopy.MI = 0; // Mark this one as done.
1922 ProgressMade = true;
1933 /// Return true if the two specified registers belong to different register
1934 /// classes. The registers may be either phys or virt regs. In the
1935 /// case where both registers are virtual registers, it would also returns
1936 /// true by reference the RegB register class in SubRC if it is a subset of
1937 /// RegA's register class.
1939 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
1940 const TargetRegisterClass *&SubRC) const {
1942 // Get the register classes for the first reg.
1943 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1944 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1945 "Shouldn't consider two physregs!");
1946 return !mri_->getRegClass(RegB)->contains(RegA);
1949 // Compare against the regclass for the second reg.
1950 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1951 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1952 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1953 if (RegClassA == RegClassB)
1955 SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
1958 return !RegClassA->contains(RegB);
1961 /// lastRegisterUse - Returns the last use of the specific register between
1962 /// cycles Start and End or NULL if there are no uses.
1964 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1965 unsigned Reg, unsigned &UseIdx) const{
1967 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1968 MachineOperand *LastUse = NULL;
1969 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1970 E = mri_->use_end(); I != E; ++I) {
1971 MachineOperand &Use = I.getOperand();
1972 MachineInstr *UseMI = Use.getParent();
1973 unsigned SrcReg, DstReg;
1974 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1975 // Ignore identity copies.
1977 unsigned Idx = li_->getInstructionIndex(UseMI);
1978 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1986 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1989 // Skip deleted instructions
1990 MachineInstr *MI = li_->getInstructionFromIndex(e);
1991 while ((e - InstrSlots::NUM) >= s && !MI) {
1992 e -= InstrSlots::NUM;
1993 MI = li_->getInstructionFromIndex(e);
1995 if (e < s || MI == NULL)
1998 // Ignore identity copies.
1999 unsigned SrcReg, DstReg;
2000 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
2001 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2002 MachineOperand &Use = MI->getOperand(i);
2003 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
2004 tri_->regsOverlap(Use.getReg(), Reg)) {
2010 e -= InstrSlots::NUM;
2017 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2018 if (TargetRegisterInfo::isPhysicalRegister(reg))
2019 cerr << tri_->getName(reg);
2021 cerr << "%reg" << reg;
2024 void SimpleRegisterCoalescing::releaseMemory() {
2025 JoinedCopies.clear();
2028 static bool isZeroLengthInterval(LiveInterval *li) {
2029 for (LiveInterval::Ranges::const_iterator
2030 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2031 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2036 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2037 /// turn the copy into an implicit def.
2039 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2040 MachineBasicBlock *MBB,
2041 unsigned DstReg, unsigned SrcReg) {
2042 MachineInstr *CopyMI = &*I;
2043 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2044 if (!li_->hasInterval(SrcReg))
2046 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2047 if (!SrcInt.empty())
2049 if (!li_->hasInterval(DstReg))
2051 LiveInterval &DstInt = li_->getInterval(DstReg);
2052 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2053 DstInt.removeValNo(DstLR->valno);
2054 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2055 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2056 CopyMI->RemoveOperand(i);
2057 bool NoUse = mri_->use_begin(SrcReg) == mri_->use_end();
2059 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2060 E = mri_->reg_end(); I != E; ) {
2061 assert(I.getOperand().isDef());
2062 MachineInstr *DefMI = &*I;
2064 // The implicit_def source has no other uses, delete it.
2065 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2066 li_->RemoveMachineInstrFromMaps(DefMI);
2067 DefMI->eraseFromParent();
2075 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2077 mri_ = &fn.getRegInfo();
2078 tm_ = &fn.getTarget();
2079 tri_ = tm_->getRegisterInfo();
2080 tii_ = tm_->getInstrInfo();
2081 li_ = &getAnalysis<LiveIntervals>();
2082 loopInfo = &getAnalysis<MachineLoopInfo>();
2084 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2085 << "********** Function: "
2086 << ((Value*)mf_->getFunction())->getName() << '\n';
2088 allocatableRegs_ = tri_->getAllocatableSet(fn);
2089 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2090 E = tri_->regclass_end(); I != E; ++I)
2091 allocatableRCRegs_.insert(std::make_pair(*I,
2092 tri_->getAllocatableSet(fn, *I)));
2094 // Join (coalesce) intervals if requested.
2095 if (EnableJoining) {
2097 DOUT << "********** INTERVALS POST JOINING **********\n";
2098 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2099 I->second.print(DOUT, tri_);
2104 // Perform a final pass over the instructions and compute spill weights
2105 // and remove identity moves.
2106 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2107 mbbi != mbbe; ++mbbi) {
2108 MachineBasicBlock* mbb = mbbi;
2109 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2111 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2113 MachineInstr *MI = mii;
2114 unsigned SrcReg, DstReg;
2115 if (JoinedCopies.count(MI)) {
2116 // Delete all coalesced copies.
2117 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2118 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2119 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2120 "Unrecognized copy instruction");
2121 DstReg = MI->getOperand(0).getReg();
2123 if (MI->registerDefIsDead(DstReg)) {
2124 LiveInterval &li = li_->getInterval(DstReg);
2125 if (!ShortenDeadCopySrcLiveRange(li, MI))
2126 ShortenDeadCopyLiveRange(li, MI);
2128 li_->RemoveMachineInstrFromMaps(MI);
2129 mii = mbbi->erase(mii);
2134 // If the move will be an identity move delete it
2135 bool isMove = tii_->isMoveInstr(*mii, SrcReg, DstReg);
2136 if (isMove && SrcReg == DstReg) {
2137 if (li_->hasInterval(SrcReg)) {
2138 LiveInterval &RegInt = li_->getInterval(SrcReg);
2139 // If def of this move instruction is dead, remove its live range
2140 // from the dstination register's live interval.
2141 if (mii->registerDefIsDead(DstReg)) {
2142 if (!ShortenDeadCopySrcLiveRange(RegInt, mii))
2143 ShortenDeadCopyLiveRange(RegInt, mii);
2146 li_->RemoveMachineInstrFromMaps(mii);
2147 mii = mbbi->erase(mii);
2149 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2150 SmallSet<unsigned, 4> UniqueUses;
2151 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
2152 const MachineOperand &mop = mii->getOperand(i);
2153 if (mop.isRegister() && mop.getReg() &&
2154 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2155 unsigned reg = mop.getReg();
2156 // Multiple uses of reg by the same instruction. It should not
2157 // contribute to spill weight again.
2158 if (UniqueUses.count(reg) != 0)
2160 LiveInterval &RegInt = li_->getInterval(reg);
2162 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2163 UniqueUses.insert(reg);
2171 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2172 LiveInterval &LI = I->second;
2173 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2174 // If the live interval length is essentially zero, i.e. in every live
2175 // range the use follows def immediately, it doesn't make sense to spill
2176 // it and hope it will be easier to allocate for this li.
2177 if (isZeroLengthInterval(&LI))
2178 LI.weight = HUGE_VALF;
2180 bool isLoad = false;
2181 if (li_->isReMaterializable(LI, isLoad)) {
2182 // If all of the definitions of the interval are re-materializable,
2183 // it is a preferred candidate for spilling. If non of the defs are
2184 // loads, then it's potentially very cheap to re-materialize.
2185 // FIXME: this gets much more complicated once we support non-trivial
2186 // re-materialization.
2194 // Slightly prefer live interval that has been assigned a preferred reg.
2198 // Divide the weight of the interval by its size. This encourages
2199 // spilling of intervals that are large and have few uses, and
2200 // discourages spilling of small intervals with many uses.
2201 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2209 /// print - Implement the dump method.
2210 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2214 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2215 return new SimpleRegisterCoalescing();
2218 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2219 DEFINING_FILE_FOR(SimpleRegisterCoalescing)