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;
46 EnableJoining("join-liveintervals",
47 cl::desc("Coalesce copies (default=true)"),
51 NewHeuristic("new-coalescer-heuristic",
52 cl::desc("Use new coalescer heuristic"),
55 static RegisterPass<SimpleRegisterCoalescing>
56 X("simple-register-coalescing", "Simple Register Coalescing");
58 // Declare that we implement the RegisterCoalescer interface
59 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
61 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
63 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addPreserved<LiveIntervals>();
65 AU.addPreserved<MachineLoopInfo>();
66 AU.addPreservedID(MachineDominatorsID);
67 AU.addPreservedID(PHIEliminationID);
68 AU.addPreservedID(TwoAddressInstructionPassID);
69 AU.addRequired<LiveVariables>();
70 AU.addRequired<LiveIntervals>();
71 AU.addRequired<MachineLoopInfo>();
72 MachineFunctionPass::getAnalysisUsage(AU);
75 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
76 /// being the source and IntB being the dest, thus this defines a value number
77 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
78 /// see if we can merge these two pieces of B into a single value number,
79 /// eliminating a copy. For example:
83 /// B1 = A3 <- this copy
85 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
86 /// value number to be replaced with B0 (which simplifies the B liveinterval).
88 /// This returns true if an interval was modified.
90 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
92 MachineInstr *CopyMI) {
93 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
95 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
97 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
98 if (BLR == IntB.end()) // Should never happen!
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 if (ALR == IntA.end()) // Should never happen!
112 VNInfo *AValNo = ALR->valno;
114 // If AValNo is defined as a copy from IntB, we can potentially process this.
115 // Get the instruction that defines this value number.
116 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
117 if (!SrcReg) return false; // Not defined by a copy.
119 // If the value number is not defined by a copy instruction, ignore it.
121 // If the source register comes from an interval other than IntB, we can't
123 if (SrcReg != IntB.reg) return false;
125 // Get the LiveRange in IntB that this value number starts with.
126 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
127 if (ValLR == IntB.end()) // Should never happen!
130 // Make sure that the end of the live range is inside the same block as
132 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
134 ValLREndInst->getParent() != CopyMI->getParent()) return false;
136 // Okay, we now know that ValLR ends in the same block that the CopyMI
137 // live-range starts. If there are no intervening live ranges between them in
138 // IntB, we can merge them.
139 if (ValLR+1 != BLR) return false;
141 // If a live interval is a physical register, conservatively check if any
142 // of its sub-registers is overlapping the live interval of the virtual
143 // register. If so, do not coalesce.
144 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
145 *tri_->getSubRegisters(IntB.reg)) {
146 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
147 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
148 DOUT << "Interfere with sub-register ";
149 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
154 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
156 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
157 // We are about to delete CopyMI, so need to remove it as the 'instruction
158 // that defines this value #'. Update the the valnum with the new defining
160 BValNo->def = FillerStart;
163 // Okay, we can merge them. We need to insert a new liverange:
164 // [ValLR.end, BLR.begin) of either value number, then we merge the
165 // two value numbers.
166 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
168 // If the IntB live range is assigned to a physical register, and if that
169 // physreg has aliases,
170 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
171 // Update the liveintervals of sub-registers.
172 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
173 LiveInterval &AliasLI = li_->getInterval(*AS);
174 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
175 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
179 // Okay, merge "B1" into the same value number as "B0".
180 if (BValNo != ValLR->valno)
181 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
182 DOUT << " result = "; IntB.print(DOUT, tri_);
185 // If the source instruction was killing the source register before the
186 // merge, unset the isKill marker given the live range has been extended.
187 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
189 ValLREndInst->getOperand(UIdx).setIsKill(false);
195 /// HasOtherReachingDefs - Return true if there are definitions of IntB
196 /// other than BValNo val# that can reach uses of AValno val# of IntA.
197 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
201 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
203 if (AI->valno != AValNo) continue;
204 LiveInterval::Ranges::iterator BI =
205 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
206 if (BI != IntB.ranges.begin())
208 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
209 if (BI->valno == BValNo)
211 if (BI->start <= AI->start && BI->end > AI->start)
213 if (BI->start > AI->start && BI->start < AI->end)
220 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
221 /// being the source and IntB being the dest, thus this defines a value number
222 /// in IntB. If the source value number (in IntA) is defined by a commutable
223 /// instruction and its other operand is coalesced to the copy dest register,
224 /// see if we can transform the copy into a noop by commuting the definition. For
227 /// A3 = op A2 B0<kill>
229 /// B1 = A3 <- this copy
231 /// = op A3 <- more uses
235 /// B2 = op B0 A2<kill>
237 /// B1 = B2 <- now an identify copy
239 /// = op B2 <- more uses
241 /// This returns true if an interval was modified.
243 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
245 MachineInstr *CopyMI) {
246 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
248 // FIXME: For now, only eliminate the copy by commuting its def when the
249 // source register is a virtual register. We want to guard against cases
250 // where the copy is a back edge copy and commuting the def lengthen the
251 // live interval of the source register to the entire loop.
252 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
255 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
256 // the example above.
257 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
258 if (BLR == IntB.end()) // Should never happen!
260 VNInfo *BValNo = BLR->valno;
262 // Get the location that B is defined at. Two options: either this value has
263 // an unknown definition point or it is defined at CopyIdx. If unknown, we
265 if (!BValNo->copy) return false;
266 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
268 // AValNo is the value number in A that defines the copy, A3 in the example.
269 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
270 if (ALR == IntA.end()) // Should never happen!
272 VNInfo *AValNo = ALR->valno;
273 // If other defs can reach uses of this def, then it's not safe to perform
275 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
277 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
278 const TargetInstrDesc &TID = DefMI->getDesc();
280 if (!TID.isCommutable() ||
281 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
284 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
285 unsigned NewReg = NewDstMO.getReg();
286 if (NewReg != IntB.reg || !NewDstMO.isKill())
289 // Make sure there are no other definitions of IntB that would reach the
290 // uses which the new definition can reach.
291 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
294 // If some of the uses of IntA.reg is already coalesced away, return false.
295 // It's not possible to determine whether it's safe to perform the coalescing.
296 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
297 UE = mri_->use_end(); UI != UE; ++UI) {
298 MachineInstr *UseMI = &*UI;
299 unsigned UseIdx = li_->getInstructionIndex(UseMI);
300 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
301 if (ULR == IntA.end())
303 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
307 // At this point we have decided that it is legal to do this
308 // transformation. Start by commuting the instruction.
309 MachineBasicBlock *MBB = DefMI->getParent();
310 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
313 if (NewMI != DefMI) {
314 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
315 MBB->insert(DefMI, NewMI);
318 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
319 NewMI->getOperand(OpIdx).setIsKill();
321 bool BHasPHIKill = BValNo->hasPHIKill;
322 SmallVector<VNInfo*, 4> BDeadValNos;
323 SmallVector<unsigned, 4> BKills;
324 std::map<unsigned, unsigned> BExtend;
326 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
335 // then do not add kills of A to the newly created B interval.
336 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
338 BExtend[ALR->end] = BLR->end;
340 // Update uses of IntA of the specific Val# with IntB.
341 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
342 UE = mri_->use_end(); UI != UE;) {
343 MachineOperand &UseMO = UI.getOperand();
344 MachineInstr *UseMI = &*UI;
346 if (JoinedCopies.count(UseMI))
348 unsigned UseIdx = li_->getInstructionIndex(UseMI);
349 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
350 if (ULR == IntA.end() || ULR->valno != AValNo)
352 UseMO.setReg(NewReg);
355 if (UseMO.isKill()) {
357 UseMO.setIsKill(false);
359 BKills.push_back(li_->getUseIndex(UseIdx)+1);
361 unsigned SrcReg, DstReg;
362 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
364 if (DstReg == IntB.reg) {
365 // This copy will become a noop. If it's defining a new val#,
366 // remove that val# as well. However this live range is being
367 // extended to the end of the existing live range defined by the copy.
368 unsigned DefIdx = li_->getDefIndex(UseIdx);
369 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
370 BHasPHIKill |= DLR->valno->hasPHIKill;
371 assert(DLR->valno->def == DefIdx);
372 BDeadValNos.push_back(DLR->valno);
373 BExtend[DLR->start] = DLR->end;
374 JoinedCopies.insert(UseMI);
375 // If this is a kill but it's going to be removed, the last use
376 // of the same val# is the new kill.
382 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
383 // simply extend BLR if CopyMI doesn't end the range.
384 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
386 IntB.removeValNo(BValNo);
387 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
388 IntB.removeValNo(BDeadValNos[i]);
389 VNInfo *ValNo = IntB.getNextValue(AValNo->def, 0, li_->getVNInfoAllocator());
390 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
392 if (AI->valno != AValNo) continue;
393 unsigned End = AI->end;
394 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
395 if (EI != BExtend.end())
397 IntB.addRange(LiveRange(AI->start, End, ValNo));
399 IntB.addKills(ValNo, BKills);
400 ValNo->hasPHIKill = BHasPHIKill;
402 DOUT << " result = "; IntB.print(DOUT, tri_);
405 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
406 IntA.removeValNo(AValNo);
407 DOUT << " result = "; IntA.print(DOUT, tri_);
414 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
416 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
417 unsigned DstReg) const {
418 MachineBasicBlock *MBB = CopyMI->getParent();
419 const MachineLoop *L = loopInfo->getLoopFor(MBB);
422 if (MBB != L->getLoopLatch())
425 LiveInterval &LI = li_->getInterval(DstReg);
426 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
427 LiveInterval::const_iterator DstLR =
428 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
429 if (DstLR == LI.end())
431 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
432 if (DstLR->valno->kills.size() == 1 &&
433 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
438 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
439 /// update the subregister number if it is not zero. If DstReg is a
440 /// physical register and the existing subregister number of the def / use
441 /// being updated is not zero, make sure to set it to the correct physical
444 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
446 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
447 if (DstIsPhys && SubIdx) {
448 // Figure out the real physical register we are updating with.
449 DstReg = tri_->getSubReg(DstReg, SubIdx);
453 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
454 E = mri_->reg_end(); I != E; ) {
455 MachineOperand &O = I.getOperand();
456 MachineInstr *UseMI = &*I;
458 unsigned OldSubIdx = O.getSubReg();
460 unsigned UseDstReg = DstReg;
462 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
466 // Sub-register indexes goes from small to large. e.g.
467 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
468 // EAX: 1 -> AL, 2 -> AX
469 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
470 // sub-register 2 is also AX.
471 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
472 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
475 // Remove would-be duplicated kill marker.
476 if (O.isKill() && UseMI->killsRegister(DstReg))
483 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
484 /// registers due to insert_subreg coalescing. e.g.
486 /// r1025 = implicit_def
487 /// r1025 = insert_subreg r1025, r1024
491 /// r1025 = implicit_def
492 /// r1025 = insert_subreg r1025, r1025
495 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
496 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
497 E = mri_->reg_end(); I != E; ) {
498 MachineOperand &O = I.getOperand();
499 MachineInstr *DefMI = &*I;
503 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
505 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
507 li_->RemoveMachineInstrFromMaps(DefMI);
508 DefMI->eraseFromParent();
512 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
513 /// due to live range lengthening as the result of coalescing.
514 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
516 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
517 UE = mri_->use_end(); UI != UE; ++UI) {
518 MachineOperand &UseMO = UI.getOperand();
519 if (UseMO.isKill()) {
520 MachineInstr *UseMI = UseMO.getParent();
522 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
524 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
525 if (JoinedCopies.count(UseMI))
527 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
528 if (!LI.isKill(UI->valno, UseIdx+1))
529 UseMO.setIsKill(false);
534 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
535 /// from a physical register live interval as well as from the live intervals
536 /// of its sub-registers.
537 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
538 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
539 li.removeRange(Start, End, true);
540 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
541 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
542 if (!li_->hasInterval(*SR))
544 LiveInterval &sli = li_->getInterval(*SR);
545 unsigned RemoveEnd = Start;
546 while (RemoveEnd != End) {
547 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
550 RemoveEnd = (LR->end < End) ? LR->end : End;
551 sli.removeRange(Start, RemoveEnd, true);
558 /// removeIntervalIfEmpty - Check if the live interval of a physical register
559 /// is empty, if so remove it and also remove the empty intervals of its
560 /// sub-registers. Return true if live interval is removed.
561 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
562 const TargetRegisterInfo *tri_) {
564 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
565 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
566 if (!li_->hasInterval(*SR))
568 LiveInterval &sli = li_->getInterval(*SR);
570 li_->removeInterval(*SR);
572 li_->removeInterval(li.reg);
578 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
579 /// Return true if live interval is removed.
580 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
581 MachineInstr *CopyMI) {
582 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
583 LiveInterval::iterator MLR =
584 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
586 return false; // Already removed by ShortenDeadCopySrcLiveRange.
587 unsigned RemoveStart = MLR->start;
588 unsigned RemoveEnd = MLR->end;
589 // Remove the liverange that's defined by this.
590 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
591 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
592 return removeIntervalIfEmpty(li, li_, tri_);
597 /// PropagateDeadness - Propagate the dead marker to the instruction which
598 /// defines the val#.
599 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
600 unsigned &LRStart, LiveIntervals *li_,
601 const TargetRegisterInfo* tri_) {
602 MachineInstr *DefMI =
603 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
604 if (DefMI && DefMI != CopyMI) {
605 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
607 DefMI->getOperand(DeadIdx).setIsDead();
608 // A dead def should have a single cycle interval.
614 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
615 /// fallthoughs to SuccMBB.
616 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
617 MachineBasicBlock *SuccMBB,
618 const TargetInstrInfo *tii_) {
621 MachineBasicBlock *TBB = 0, *FBB = 0;
622 std::vector<MachineOperand> Cond;
623 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
624 MBB->isSuccessor(SuccMBB);
627 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
628 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
629 /// ends the live range there. If there isn't another use, then this live range
630 /// is dead. Return true if live interval is removed.
632 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
633 MachineInstr *CopyMI) {
634 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
636 // FIXME: special case: function live in. It can be a general case if the
637 // first instruction index starts at > 0 value.
638 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
639 // Live-in to the function but dead. Remove it from entry live-in set.
640 if (mf_->begin()->isLiveIn(li.reg))
641 mf_->begin()->removeLiveIn(li.reg);
642 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
643 removeRange(li, LR->start, LR->end, li_, tri_);
644 return removeIntervalIfEmpty(li, li_, tri_);
647 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
649 // Livein but defined by a phi.
652 unsigned RemoveStart = LR->start;
653 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
654 if (LR->end > RemoveEnd)
655 // More uses past this copy? Nothing to do.
658 MachineBasicBlock *CopyMBB = CopyMI->getParent();
659 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
661 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
664 MachineInstr *LastUseMI = LastUse->getParent();
665 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
672 // r1025<dead> = r1024<kill>
673 if (MBBStart < LR->end)
674 removeRange(li, MBBStart, LR->end, li_, tri_);
678 // There are uses before the copy, just shorten the live range to the end
680 LastUse->setIsKill();
681 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
682 unsigned SrcReg, DstReg;
683 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
685 // Last use is itself an identity code.
686 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
687 LastUseMI->getOperand(DeadIdx).setIsDead();
693 if (LR->start <= MBBStart && LR->end > MBBStart) {
694 if (LR->start == 0) {
695 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
696 // Live-in to the function but dead. Remove it from entry live-in set.
697 mf_->begin()->removeLiveIn(li.reg);
699 // FIXME: Shorten intervals in BBs that reaches this BB.
702 if (LR->valno->def == RemoveStart)
703 // If the def MI defines the val#, propagate the dead marker.
704 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
706 removeRange(li, RemoveStart, LR->end, li_, tri_);
707 return removeIntervalIfEmpty(li, li_, tri_);
710 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
711 /// from an implicit def to another register can be coalesced away.
712 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
714 LiveInterval &ImpLi) const{
715 if (!CopyMI->killsRegister(ImpLi.reg))
717 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
718 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
721 if (LR->valno->hasPHIKill)
723 if (LR->valno->def != CopyIdx)
725 // Make sure all of val# uses are copies.
726 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
727 UE = mri_->use_end(); UI != UE;) {
728 MachineInstr *UseMI = &*UI;
730 if (JoinedCopies.count(UseMI))
732 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
733 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
734 if (ULR == li.end() || ULR->valno != LR->valno)
736 // If the use is not a use, then it's not safe to coalesce the move.
737 unsigned SrcReg, DstReg;
738 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
739 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
740 UseMI->getOperand(1).getReg() == li.reg)
749 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
750 /// def and it is being removed. Turn all copies from this value# into
751 /// identity copies so they will be removed.
752 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
754 MachineInstr *ImpDef = NULL;
755 MachineOperand *LastUse = NULL;
756 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
757 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
758 RE = mri_->reg_end(); RI != RE;) {
759 MachineOperand *MO = &RI.getOperand();
760 MachineInstr *MI = &*RI;
763 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
764 assert(!ImpDef && "Multiple implicit_def defining same register?");
769 if (JoinedCopies.count(MI))
771 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
772 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
773 if (ULR == li.end() || ULR->valno != VNI)
775 // If the use is a copy, turn it into an identity copy.
776 unsigned SrcReg, DstReg;
777 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
778 // Each use MI may have multiple uses of this register. Change them all.
779 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
780 MachineOperand &MO = MI->getOperand(i);
781 if (MO.isReg() && MO.getReg() == li.reg)
784 JoinedCopies.insert(MI);
785 } else if (UseIdx > LastUseIdx) {
791 LastUse->setIsKill();
793 // Remove dead implicit_def.
794 li_->RemoveMachineInstrFromMaps(ImpDef);
795 ImpDef->eraseFromParent();
799 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
800 const TargetRegisterClass *RC,
801 const TargetRegisterInfo* TRI) {
802 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
803 unsigned SR = *SRs; ++SRs)
804 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
809 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
810 /// which are the src/dst of the copy instruction CopyMI. This returns true
811 /// if the copy was successfully coalesced away. If it is not currently
812 /// possible to coalesce this interval, but it may be possible if other
813 /// things get coalesced, then it returns true by reference in 'Again'.
814 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
815 MachineInstr *CopyMI = TheCopy.MI;
818 if (JoinedCopies.count(CopyMI))
819 return false; // Already done.
821 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
825 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
826 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
829 DstReg = CopyMI->getOperand(0).getReg();
830 SrcReg = CopyMI->getOperand(1).getReg();
831 } else if (isInsSubReg) {
832 if (CopyMI->getOperand(2).getSubReg()) {
833 DOUT << "\tSource of insert_subreg is already coalesced "
834 << "to another register.\n";
835 return false; // Not coalescable.
837 DstReg = CopyMI->getOperand(0).getReg();
838 SrcReg = CopyMI->getOperand(2).getReg();
839 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
840 assert(0 && "Unrecognized copy instruction!");
844 // If they are already joined we continue.
845 if (SrcReg == DstReg) {
846 DOUT << "\tCopy already coalesced.\n";
847 return false; // Not coalescable.
850 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
851 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
853 // If they are both physical registers, we cannot join them.
854 if (SrcIsPhys && DstIsPhys) {
855 DOUT << "\tCan not coalesce physregs.\n";
856 return false; // Not coalescable.
859 // We only join virtual registers with allocatable physical registers.
860 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
861 DOUT << "\tSrc reg is unallocatable physreg.\n";
862 return false; // Not coalescable.
864 if (DstIsPhys && !allocatableRegs_[DstReg]) {
865 DOUT << "\tDst reg is unallocatable physreg.\n";
866 return false; // Not coalescable.
869 unsigned RealDstReg = 0;
870 unsigned RealSrcReg = 0;
871 if (isExtSubReg || isInsSubReg) {
872 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
873 if (SrcIsPhys && isExtSubReg) {
874 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
875 // coalesced with AX.
876 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
878 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
879 // coalesced to a larger register so the subreg indices cancel out.
880 if (DstSubIdx != SubIdx) {
881 DOUT << "\t Sub-register indices mismatch.\n";
882 return false; // Not coalescable.
885 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
887 } else if (DstIsPhys && isInsSubReg) {
888 // EAX = INSERT_SUBREG EAX, r1024, 0
889 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
891 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
892 // coalesced to a larger register so the subreg indices cancel out.
893 if (SrcSubIdx != SubIdx) {
894 DOUT << "\t Sub-register indices mismatch.\n";
895 return false; // Not coalescable.
898 DstReg = tri_->getSubReg(DstReg, SubIdx);
900 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
901 // If this is a extract_subreg where dst is a physical register, e.g.
902 // cl = EXTRACT_SUBREG reg1024, 1
903 // then create and update the actual physical register allocated to RHS.
905 // reg1024 = INSERT_SUBREG r1024, cl, 1
906 if (CopyMI->getOperand(1).getSubReg()) {
907 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
908 << " of a super-class.\n";
909 return false; // Not coalescable.
911 const TargetRegisterClass *RC =
912 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
914 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
915 assert(RealDstReg && "Invalid extra_subreg instruction!");
917 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
918 assert(RealSrcReg && "Invalid extra_subreg instruction!");
921 // For this type of EXTRACT_SUBREG, conservatively
922 // check if the live interval of the source register interfere with the
923 // actual super physical register we are trying to coalesce with.
924 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
925 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
926 if (li_->hasInterval(PhysReg) &&
927 RHS.overlaps(li_->getInterval(PhysReg))) {
928 DOUT << "Interfere with register ";
929 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
930 return false; // Not coalescable
932 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
933 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
934 DOUT << "Interfere with sub-register ";
935 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
936 return false; // Not coalescable
940 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
941 : CopyMI->getOperand(2).getSubReg();
943 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
944 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
945 // coalesced to a larger register so the subreg indices cancel out.
946 // Also check if the other larger register is of the same register
947 // class as the would be resulting register.
950 DOUT << "\t Sub-register indices mismatch.\n";
951 return false; // Not coalescable.
955 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
956 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
957 unsigned LargeRegSize =
958 li_->getInterval(LargeReg).getSize() / InstrSlots::NUM;
959 unsigned SmallRegSize =
960 li_->getInterval(SmallReg).getSize() / InstrSlots::NUM;
961 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
962 unsigned Threshold = allocatableRCRegs_[RC].count();
963 // Be conservative. If both sides are virtual registers, do not coalesce
964 // if this will cause a high use density interval to target a smaller
966 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
967 LiveVariables::VarInfo &svi = lv_->getVarInfo(LargeReg);
968 LiveVariables::VarInfo &dvi = lv_->getVarInfo(SmallReg);
969 if ((float)dvi.NumUses / SmallRegSize <
970 (float)svi.NumUses / LargeRegSize) {
971 Again = true; // May be possible to coalesce later.
977 } else if (differingRegisterClasses(SrcReg, DstReg)) {
978 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
979 // with another? If it's the resulting destination register, then
980 // the subidx must be propagated to uses (but only those defined
981 // by the EXTRACT_SUBREG). If it's being coalesced into another
982 // register, it should be safe because register is assumed to have
983 // the register class of the super-register.
985 // If they are not of the same register class, we cannot join them.
986 DOUT << "\tSrc/Dest are different register classes.\n";
987 // Allow the coalescer to try again in case either side gets coalesced to
988 // a physical register that's compatible with the other side. e.g.
989 // r1024 = MOV32to32_ r1025
990 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
991 Again = true; // May be possible to coalesce later.
995 LiveInterval &SrcInt = li_->getInterval(SrcReg);
996 LiveInterval &DstInt = li_->getInterval(DstReg);
997 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
998 "Register mapping is horribly broken!");
1000 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1001 DOUT << " and "; DstInt.print(DOUT, tri_);
1004 // Check if it is necessary to propagate "isDead" property.
1005 if (!isExtSubReg && !isInsSubReg) {
1006 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1007 bool isDead = mopd->isDead();
1009 // We need to be careful about coalescing a source physical register with a
1010 // virtual register. Once the coalescing is done, it cannot be broken and
1011 // these are not spillable! If the destination interval uses are far away,
1012 // think twice about coalescing them!
1013 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1014 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1015 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1016 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1017 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1018 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1019 if (TheCopy.isBackEdge)
1020 Threshold *= 2; // Favors back edge copies.
1022 // If the virtual register live interval is long but it has low use desity,
1023 // do not join them, instead mark the physical register as its allocation
1025 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
1026 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
1027 if (Length > Threshold &&
1028 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
1029 JoinVInt.preference = JoinPReg;
1031 DOUT << "\tMay tie down a physical register, abort!\n";
1032 Again = true; // May be possible to coalesce later.
1038 // Okay, attempt to join these two intervals. On failure, this returns false.
1039 // Otherwise, if one of the intervals being joined is a physreg, this method
1040 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1041 // been modified, so we can use this information below to update aliases.
1042 bool Swapped = false;
1043 // If SrcInt is implicitly defined, it's safe to coalesce.
1044 bool isEmpty = SrcInt.empty();
1045 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1046 // Only coalesce an empty interval (defined by implicit_def) with
1047 // another interval which has a valno defined by the CopyMI and the CopyMI
1048 // is a kill of the implicit def.
1049 DOUT << "Not profitable!\n";
1053 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1054 // Coalescing failed.
1056 // If we can eliminate the copy without merging the live ranges, do so now.
1057 if (!isExtSubReg && !isInsSubReg &&
1058 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1059 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1060 JoinedCopies.insert(CopyMI);
1064 // Otherwise, we are unable to join the intervals.
1065 DOUT << "Interference!\n";
1066 Again = true; // May be possible to coalesce later.
1070 LiveInterval *ResSrcInt = &SrcInt;
1071 LiveInterval *ResDstInt = &DstInt;
1073 std::swap(SrcReg, DstReg);
1074 std::swap(ResSrcInt, ResDstInt);
1076 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1077 "LiveInterval::join didn't work right!");
1079 // If we're about to merge live ranges into a physical register live range,
1080 // we have to update any aliased register's live ranges to indicate that they
1081 // have clobbered values for this range.
1082 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1083 // If this is a extract_subreg where dst is a physical register, e.g.
1084 // cl = EXTRACT_SUBREG reg1024, 1
1085 // then create and update the actual physical register allocated to RHS.
1086 if (RealDstReg || RealSrcReg) {
1087 LiveInterval &RealInt =
1088 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1089 SmallSet<const VNInfo*, 4> CopiedValNos;
1090 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1091 E = ResSrcInt->ranges.end(); I != E; ++I) {
1092 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1093 assert(DstLR && "Invalid joined interval!");
1094 const VNInfo *DstValNo = DstLR->valno;
1095 if (CopiedValNos.insert(DstValNo)) {
1096 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1097 li_->getVNInfoAllocator());
1098 ValNo->hasPHIKill = DstValNo->hasPHIKill;
1099 RealInt.addKills(ValNo, DstValNo->kills);
1100 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1104 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1107 // Update the liveintervals of sub-registers.
1108 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1109 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1110 li_->getVNInfoAllocator());
1112 // Merge use info if the destination is a virtual register.
1113 LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
1114 LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
1115 dVI.NumUses += sVI.NumUses;
1118 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1119 // larger super-register.
1120 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1121 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1122 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1123 std::swap(SrcReg, DstReg);
1124 std::swap(ResSrcInt, ResDstInt);
1129 // Add all copies that define val# in the source interval into the queue.
1130 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1131 e = ResSrcInt->vni_end(); i != e; ++i) {
1132 const VNInfo *vni = *i;
1133 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1135 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1136 unsigned NewSrcReg, NewDstReg;
1138 JoinedCopies.count(CopyMI) == 0 &&
1139 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1140 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
1141 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1142 isBackEdgeCopy(CopyMI, DstReg)));
1147 // Remember to delete the copy instruction.
1148 JoinedCopies.insert(CopyMI);
1150 // Some live range has been lengthened due to colaescing, eliminate the
1151 // unnecessary kills.
1152 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1153 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1154 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1156 // SrcReg is guarateed to be the register whose live interval that is
1158 li_->removeInterval(SrcReg);
1162 // r1024 = implicit_def
1165 RemoveDeadImpDef(DstReg, *ResDstInt);
1166 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1169 // Now the copy is being coalesced away, the val# previously defined
1170 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1171 // length interval. Remove the val#.
1172 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1173 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1174 VNInfo *ImpVal = LR->valno;
1175 assert(ImpVal->def == CopyIdx);
1176 unsigned NextDef = LR->end;
1177 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1178 ResDstInt->removeValNo(ImpVal);
1179 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1180 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1181 // Special case: vr1024 = implicit_def
1182 // vr1024 = insert_subreg vr1024, vr1025, c
1183 // The insert_subreg becomes a "copy" that defines a val# which can itself
1184 // be coalesced away.
1185 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1186 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1187 LR->valno->copy = DefMI;
1191 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1198 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1199 /// compute what the resultant value numbers for each value in the input two
1200 /// ranges will be. This is complicated by copies between the two which can
1201 /// and will commonly cause multiple value numbers to be merged into one.
1203 /// VN is the value number that we're trying to resolve. InstDefiningValue
1204 /// keeps track of the new InstDefiningValue assignment for the result
1205 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1206 /// whether a value in this or other is a copy from the opposite set.
1207 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1208 /// already been assigned.
1210 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1211 /// contains the value number the copy is from.
1213 static unsigned ComputeUltimateVN(VNInfo *VNI,
1214 SmallVector<VNInfo*, 16> &NewVNInfo,
1215 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1216 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1217 SmallVector<int, 16> &ThisValNoAssignments,
1218 SmallVector<int, 16> &OtherValNoAssignments) {
1219 unsigned VN = VNI->id;
1221 // If the VN has already been computed, just return it.
1222 if (ThisValNoAssignments[VN] >= 0)
1223 return ThisValNoAssignments[VN];
1224 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1226 // If this val is not a copy from the other val, then it must be a new value
1227 // number in the destination.
1228 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1229 if (I == ThisFromOther.end()) {
1230 NewVNInfo.push_back(VNI);
1231 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1233 VNInfo *OtherValNo = I->second;
1235 // Otherwise, this *is* a copy from the RHS. If the other side has already
1236 // been computed, return it.
1237 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1238 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1240 // Mark this value number as currently being computed, then ask what the
1241 // ultimate value # of the other value is.
1242 ThisValNoAssignments[VN] = -2;
1243 unsigned UltimateVN =
1244 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1245 OtherValNoAssignments, ThisValNoAssignments);
1246 return ThisValNoAssignments[VN] = UltimateVN;
1249 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1250 return std::find(V.begin(), V.end(), Val) != V.end();
1253 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1254 /// the specified live interval is defined by a copy from the specified
1256 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1259 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1262 if (LR->valno->def == ~0U &&
1263 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1264 *tri_->getSuperRegisters(li.reg)) {
1265 // It's a sub-register live interval, we may not have precise information.
1267 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1268 unsigned SrcReg, DstReg;
1269 if (tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1270 DstReg == li.reg && SrcReg == Reg) {
1271 // Cache computed info.
1272 LR->valno->def = LR->start;
1273 LR->valno->copy = DefMI;
1280 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1281 /// caller of this method must guarantee that the RHS only contains a single
1282 /// value number and that the RHS is not defined by a copy from this
1283 /// interval. This returns false if the intervals are not joinable, or it
1284 /// joins them and returns true.
1285 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1286 assert(RHS.containsOneValue());
1288 // Some number (potentially more than one) value numbers in the current
1289 // interval may be defined as copies from the RHS. Scan the overlapping
1290 // portions of the LHS and RHS, keeping track of this and looking for
1291 // overlapping live ranges that are NOT defined as copies. If these exist, we
1294 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1295 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1297 if (LHSIt->start < RHSIt->start) {
1298 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1299 if (LHSIt != LHS.begin()) --LHSIt;
1300 } else if (RHSIt->start < LHSIt->start) {
1301 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1302 if (RHSIt != RHS.begin()) --RHSIt;
1305 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1308 // Determine if these live intervals overlap.
1309 bool Overlaps = false;
1310 if (LHSIt->start <= RHSIt->start)
1311 Overlaps = LHSIt->end > RHSIt->start;
1313 Overlaps = RHSIt->end > LHSIt->start;
1315 // If the live intervals overlap, there are two interesting cases: if the
1316 // LHS interval is defined by a copy from the RHS, it's ok and we record
1317 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1318 // coalesce these live ranges and we bail out.
1320 // If we haven't already recorded that this value # is safe, check it.
1321 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1322 // Copy from the RHS?
1323 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1324 return false; // Nope, bail out.
1326 EliminatedLHSVals.push_back(LHSIt->valno);
1329 // We know this entire LHS live range is okay, so skip it now.
1330 if (++LHSIt == LHSEnd) break;
1334 if (LHSIt->end < RHSIt->end) {
1335 if (++LHSIt == LHSEnd) break;
1337 // One interesting case to check here. It's possible that we have
1338 // something like "X3 = Y" which defines a new value number in the LHS,
1339 // and is the last use of this liverange of the RHS. In this case, we
1340 // want to notice this copy (so that it gets coalesced away) even though
1341 // the live ranges don't actually overlap.
1342 if (LHSIt->start == RHSIt->end) {
1343 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1344 // We already know that this value number is going to be merged in
1345 // if coalescing succeeds. Just skip the liverange.
1346 if (++LHSIt == LHSEnd) break;
1348 // Otherwise, if this is a copy from the RHS, mark it as being merged
1350 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1351 EliminatedLHSVals.push_back(LHSIt->valno);
1353 // We know this entire LHS live range is okay, so skip it now.
1354 if (++LHSIt == LHSEnd) break;
1359 if (++RHSIt == RHSEnd) break;
1363 // If we got here, we know that the coalescing will be successful and that
1364 // the value numbers in EliminatedLHSVals will all be merged together. Since
1365 // the most common case is that EliminatedLHSVals has a single number, we
1366 // optimize for it: if there is more than one value, we merge them all into
1367 // the lowest numbered one, then handle the interval as if we were merging
1368 // with one value number.
1370 if (EliminatedLHSVals.size() > 1) {
1371 // Loop through all the equal value numbers merging them into the smallest
1373 VNInfo *Smallest = EliminatedLHSVals[0];
1374 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1375 if (EliminatedLHSVals[i]->id < Smallest->id) {
1376 // Merge the current notion of the smallest into the smaller one.
1377 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1378 Smallest = EliminatedLHSVals[i];
1380 // Merge into the smallest.
1381 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1384 LHSValNo = Smallest;
1385 } else if (EliminatedLHSVals.empty()) {
1386 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1387 *tri_->getSuperRegisters(LHS.reg))
1388 // Imprecise sub-register information. Can't handle it.
1390 assert(0 && "No copies from the RHS?");
1392 LHSValNo = EliminatedLHSVals[0];
1395 // Okay, now that there is a single LHS value number that we're merging the
1396 // RHS into, update the value number info for the LHS to indicate that the
1397 // value number is defined where the RHS value number was.
1398 const VNInfo *VNI = RHS.getValNumInfo(0);
1399 LHSValNo->def = VNI->def;
1400 LHSValNo->copy = VNI->copy;
1402 // Okay, the final step is to loop over the RHS live intervals, adding them to
1404 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1405 LHS.addKills(LHSValNo, VNI->kills);
1406 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1407 LHS.weight += RHS.weight;
1408 if (RHS.preference && !LHS.preference)
1409 LHS.preference = RHS.preference;
1414 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1415 /// returns false. Otherwise, if one of the intervals being joined is a
1416 /// physreg, this method always canonicalizes LHS to be it. The output
1417 /// "RHS" will not have been modified, so we can use this information
1418 /// below to update aliases.
1419 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1420 LiveInterval &RHS, bool &Swapped) {
1421 // Compute the final value assignment, assuming that the live ranges can be
1423 SmallVector<int, 16> LHSValNoAssignments;
1424 SmallVector<int, 16> RHSValNoAssignments;
1425 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1426 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1427 SmallVector<VNInfo*, 16> NewVNInfo;
1429 // If a live interval is a physical register, conservatively check if any
1430 // of its sub-registers is overlapping the live interval of the virtual
1431 // register. If so, do not coalesce.
1432 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1433 *tri_->getSubRegisters(LHS.reg)) {
1434 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1435 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1436 DOUT << "Interfere with sub-register ";
1437 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1440 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1441 *tri_->getSubRegisters(RHS.reg)) {
1442 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1443 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1444 DOUT << "Interfere with sub-register ";
1445 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1450 // Compute ultimate value numbers for the LHS and RHS values.
1451 if (RHS.containsOneValue()) {
1452 // Copies from a liveinterval with a single value are simple to handle and
1453 // very common, handle the special case here. This is important, because
1454 // often RHS is small and LHS is large (e.g. a physreg).
1456 // Find out if the RHS is defined as a copy from some value in the LHS.
1457 int RHSVal0DefinedFromLHS = -1;
1459 VNInfo *RHSValNoInfo = NULL;
1460 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1461 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1462 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1463 // If RHS is not defined as a copy from the LHS, we can use simpler and
1464 // faster checks to see if the live ranges are coalescable. This joiner
1465 // can't swap the LHS/RHS intervals though.
1466 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1467 return SimpleJoin(LHS, RHS);
1469 RHSValNoInfo = RHSValNoInfo0;
1472 // It was defined as a copy from the LHS, find out what value # it is.
1473 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1474 RHSValID = RHSValNoInfo->id;
1475 RHSVal0DefinedFromLHS = RHSValID;
1478 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1479 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1480 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1482 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1483 // should now get updated.
1484 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1487 unsigned VN = VNI->id;
1488 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1489 if (LHSSrcReg != RHS.reg) {
1490 // If this is not a copy from the RHS, its value number will be
1491 // unmodified by the coalescing.
1492 NewVNInfo[VN] = VNI;
1493 LHSValNoAssignments[VN] = VN;
1494 } else if (RHSValID == -1) {
1495 // Otherwise, it is a copy from the RHS, and we don't already have a
1496 // value# for it. Keep the current value number, but remember it.
1497 LHSValNoAssignments[VN] = RHSValID = VN;
1498 NewVNInfo[VN] = RHSValNoInfo;
1499 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1501 // Otherwise, use the specified value #.
1502 LHSValNoAssignments[VN] = RHSValID;
1503 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1504 NewVNInfo[VN] = RHSValNoInfo;
1505 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1509 NewVNInfo[VN] = VNI;
1510 LHSValNoAssignments[VN] = VN;
1514 assert(RHSValID != -1 && "Didn't find value #?");
1515 RHSValNoAssignments[0] = RHSValID;
1516 if (RHSVal0DefinedFromLHS != -1) {
1517 // This path doesn't go through ComputeUltimateVN so just set
1519 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1522 // Loop over the value numbers of the LHS, seeing if any are defined from
1524 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1527 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1530 // DstReg is known to be a register in the LHS interval. If the src is
1531 // from the RHS interval, we can use its value #.
1532 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1535 // Figure out the value # from the RHS.
1536 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1539 // Loop over the value numbers of the RHS, seeing if any are defined from
1541 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1544 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1547 // DstReg is known to be a register in the RHS interval. If the src is
1548 // from the LHS interval, we can use its value #.
1549 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1552 // Figure out the value # from the LHS.
1553 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1556 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1557 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1558 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1560 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1563 unsigned VN = VNI->id;
1564 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1566 ComputeUltimateVN(VNI, NewVNInfo,
1567 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1568 LHSValNoAssignments, RHSValNoAssignments);
1570 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1573 unsigned VN = VNI->id;
1574 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1576 // If this value number isn't a copy from the LHS, it's a new number.
1577 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1578 NewVNInfo.push_back(VNI);
1579 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1583 ComputeUltimateVN(VNI, NewVNInfo,
1584 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1585 RHSValNoAssignments, LHSValNoAssignments);
1589 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1590 // interval lists to see if these intervals are coalescable.
1591 LiveInterval::const_iterator I = LHS.begin();
1592 LiveInterval::const_iterator IE = LHS.end();
1593 LiveInterval::const_iterator J = RHS.begin();
1594 LiveInterval::const_iterator JE = RHS.end();
1596 // Skip ahead until the first place of potential sharing.
1597 if (I->start < J->start) {
1598 I = std::upper_bound(I, IE, J->start);
1599 if (I != LHS.begin()) --I;
1600 } else if (J->start < I->start) {
1601 J = std::upper_bound(J, JE, I->start);
1602 if (J != RHS.begin()) --J;
1606 // Determine if these two live ranges overlap.
1608 if (I->start < J->start) {
1609 Overlaps = I->end > J->start;
1611 Overlaps = J->end > I->start;
1614 // If so, check value # info to determine if they are really different.
1616 // If the live range overlap will map to the same value number in the
1617 // result liverange, we can still coalesce them. If not, we can't.
1618 if (LHSValNoAssignments[I->valno->id] !=
1619 RHSValNoAssignments[J->valno->id])
1623 if (I->end < J->end) {
1632 // Update kill info. Some live ranges are extended due to copy coalescing.
1633 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1634 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1635 VNInfo *VNI = I->first;
1636 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1637 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1638 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1639 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1642 // Update kill info. Some live ranges are extended due to copy coalescing.
1643 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1644 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1645 VNInfo *VNI = I->first;
1646 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1647 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1648 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1649 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1652 // If we get here, we know that we can coalesce the live ranges. Ask the
1653 // intervals to coalesce themselves now.
1654 if ((RHS.ranges.size() > LHS.ranges.size() &&
1655 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1656 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1657 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1660 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1667 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1668 // depth of the basic block (the unsigned), and then on the MBB number.
1669 struct DepthMBBCompare {
1670 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1671 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1672 if (LHS.first > RHS.first) return true; // Deeper loops first
1673 return LHS.first == RHS.first &&
1674 LHS.second->getNumber() < RHS.second->getNumber();
1679 /// getRepIntervalSize - Returns the size of the interval that represents the
1680 /// specified register.
1682 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1683 return Rc->getRepIntervalSize(Reg);
1686 /// CopyRecSort::operator - Join priority queue sorting function.
1688 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1689 // Inner loops first.
1690 if (left.LoopDepth > right.LoopDepth)
1692 else if (left.LoopDepth == right.LoopDepth)
1693 if (left.isBackEdge && !right.isBackEdge)
1698 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1699 std::vector<CopyRec> &TryAgain) {
1700 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1702 std::vector<CopyRec> VirtCopies;
1703 std::vector<CopyRec> PhysCopies;
1704 std::vector<CopyRec> ImpDefCopies;
1705 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1706 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1708 MachineInstr *Inst = MII++;
1710 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1711 unsigned SrcReg, DstReg;
1712 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1713 DstReg = Inst->getOperand(0).getReg();
1714 SrcReg = Inst->getOperand(1).getReg();
1715 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1716 DstReg = Inst->getOperand(0).getReg();
1717 SrcReg = Inst->getOperand(2).getReg();
1718 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1721 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1722 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1724 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1726 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1727 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1728 else if (SrcIsPhys || DstIsPhys)
1729 PhysCopies.push_back(CopyRec(Inst, 0, false));
1731 VirtCopies.push_back(CopyRec(Inst, 0, false));
1738 // Try coalescing implicit copies first, followed by copies to / from
1739 // physical registers, then finally copies from virtual registers to
1740 // virtual registers.
1741 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1742 CopyRec &TheCopy = ImpDefCopies[i];
1744 if (!JoinCopy(TheCopy, Again))
1746 TryAgain.push_back(TheCopy);
1748 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1749 CopyRec &TheCopy = PhysCopies[i];
1751 if (!JoinCopy(TheCopy, Again))
1753 TryAgain.push_back(TheCopy);
1755 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1756 CopyRec &TheCopy = VirtCopies[i];
1758 if (!JoinCopy(TheCopy, Again))
1760 TryAgain.push_back(TheCopy);
1764 void SimpleRegisterCoalescing::joinIntervals() {
1765 DOUT << "********** JOINING INTERVALS ***********\n";
1768 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1770 std::vector<CopyRec> TryAgainList;
1771 if (loopInfo->begin() == loopInfo->end()) {
1772 // If there are no loops in the function, join intervals in function order.
1773 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1775 CopyCoalesceInMBB(I, TryAgainList);
1777 // Otherwise, join intervals in inner loops before other intervals.
1778 // Unfortunately we can't just iterate over loop hierarchy here because
1779 // there may be more MBB's than BB's. Collect MBB's for sorting.
1781 // Join intervals in the function prolog first. We want to join physical
1782 // registers with virtual registers before the intervals got too long.
1783 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1784 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1785 MachineBasicBlock *MBB = I;
1786 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1789 // Sort by loop depth.
1790 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1792 // Finally, join intervals in loop nest order.
1793 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1794 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1797 // Joining intervals can allow other intervals to be joined. Iteratively join
1798 // until we make no progress.
1800 SmallVector<CopyRec, 16> TryAgain;
1801 bool ProgressMade = true;
1802 while (ProgressMade) {
1803 ProgressMade = false;
1804 while (!JoinQueue->empty()) {
1805 CopyRec R = JoinQueue->pop();
1807 bool Success = JoinCopy(R, Again);
1809 ProgressMade = true;
1811 TryAgain.push_back(R);
1815 while (!TryAgain.empty()) {
1816 JoinQueue->push(TryAgain.back());
1817 TryAgain.pop_back();
1822 bool ProgressMade = true;
1823 while (ProgressMade) {
1824 ProgressMade = false;
1826 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1827 CopyRec &TheCopy = TryAgainList[i];
1830 bool Success = JoinCopy(TheCopy, Again);
1831 if (Success || !Again) {
1832 TheCopy.MI = 0; // Mark this one as done.
1833 ProgressMade = true;
1844 /// Return true if the two specified registers belong to different register
1845 /// classes. The registers may be either phys or virt regs.
1846 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1847 unsigned RegB) const {
1849 // Get the register classes for the first reg.
1850 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1851 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1852 "Shouldn't consider two physregs!");
1853 return !mri_->getRegClass(RegB)->contains(RegA);
1856 // Compare against the regclass for the second reg.
1857 const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1858 if (TargetRegisterInfo::isVirtualRegister(RegB))
1859 return RegClass != mri_->getRegClass(RegB);
1861 return !RegClass->contains(RegB);
1864 /// lastRegisterUse - Returns the last use of the specific register between
1865 /// cycles Start and End or NULL if there are no uses.
1867 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1868 unsigned Reg, unsigned &UseIdx) const{
1870 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1871 MachineOperand *LastUse = NULL;
1872 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1873 E = mri_->use_end(); I != E; ++I) {
1874 MachineOperand &Use = I.getOperand();
1875 MachineInstr *UseMI = Use.getParent();
1876 unsigned SrcReg, DstReg;
1877 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1878 // Ignore identity copies.
1880 unsigned Idx = li_->getInstructionIndex(UseMI);
1881 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1889 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1892 // Skip deleted instructions
1893 MachineInstr *MI = li_->getInstructionFromIndex(e);
1894 while ((e - InstrSlots::NUM) >= s && !MI) {
1895 e -= InstrSlots::NUM;
1896 MI = li_->getInstructionFromIndex(e);
1898 if (e < s || MI == NULL)
1901 // Ignore identity copies.
1902 unsigned SrcReg, DstReg;
1903 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1904 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1905 MachineOperand &Use = MI->getOperand(i);
1906 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1907 tri_->regsOverlap(Use.getReg(), Reg)) {
1913 e -= InstrSlots::NUM;
1920 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1921 if (TargetRegisterInfo::isPhysicalRegister(reg))
1922 cerr << tri_->getName(reg);
1924 cerr << "%reg" << reg;
1927 void SimpleRegisterCoalescing::releaseMemory() {
1928 JoinedCopies.clear();
1931 static bool isZeroLengthInterval(LiveInterval *li) {
1932 for (LiveInterval::Ranges::const_iterator
1933 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1934 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1939 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
1940 /// turn the copy into an implicit def.
1942 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
1943 MachineBasicBlock *MBB,
1944 unsigned DstReg, unsigned SrcReg) {
1945 MachineInstr *CopyMI = &*I;
1946 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1947 if (!li_->hasInterval(SrcReg))
1949 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1950 if (!SrcInt.empty())
1952 if (!li_->hasInterval(DstReg))
1954 LiveInterval &DstInt = li_->getInterval(DstReg);
1955 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
1956 DstInt.removeValNo(DstLR->valno);
1957 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
1958 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
1959 CopyMI->RemoveOperand(i);
1960 bool NoUse = mri_->use_begin(SrcReg) == mri_->use_end();
1962 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
1963 E = mri_->reg_end(); I != E; ) {
1964 assert(I.getOperand().isDef());
1965 MachineInstr *DefMI = &*I;
1967 // The implicit_def source has no other uses, delete it.
1968 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
1969 li_->RemoveMachineInstrFromMaps(DefMI);
1970 DefMI->eraseFromParent();
1978 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1980 mri_ = &fn.getRegInfo();
1981 tm_ = &fn.getTarget();
1982 tri_ = tm_->getRegisterInfo();
1983 tii_ = tm_->getInstrInfo();
1984 li_ = &getAnalysis<LiveIntervals>();
1985 lv_ = &getAnalysis<LiveVariables>();
1986 loopInfo = &getAnalysis<MachineLoopInfo>();
1988 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1989 << "********** Function: "
1990 << ((Value*)mf_->getFunction())->getName() << '\n';
1992 allocatableRegs_ = tri_->getAllocatableSet(fn);
1993 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1994 E = tri_->regclass_end(); I != E; ++I)
1995 allocatableRCRegs_.insert(std::make_pair(*I,
1996 tri_->getAllocatableSet(fn, *I)));
1998 // Join (coalesce) intervals if requested.
1999 if (EnableJoining) {
2001 DOUT << "********** INTERVALS POST JOINING **********\n";
2002 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2003 I->second.print(DOUT, tri_);
2008 // Perform a final pass over the instructions and compute spill weights
2009 // and remove identity moves.
2010 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2011 mbbi != mbbe; ++mbbi) {
2012 MachineBasicBlock* mbb = mbbi;
2013 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2015 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2017 MachineInstr *MI = mii;
2018 unsigned SrcReg, DstReg;
2019 if (JoinedCopies.count(MI)) {
2020 // Delete all coalesced copies.
2021 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2022 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2023 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2024 "Unrecognized copy instruction");
2025 DstReg = MI->getOperand(0).getReg();
2027 if (MI->registerDefIsDead(DstReg)) {
2028 LiveInterval &li = li_->getInterval(DstReg);
2029 if (!ShortenDeadCopySrcLiveRange(li, MI))
2030 ShortenDeadCopyLiveRange(li, MI);
2032 li_->RemoveMachineInstrFromMaps(MI);
2033 mii = mbbi->erase(mii);
2038 // If the move will be an identity move delete it
2039 bool isMove = tii_->isMoveInstr(*mii, SrcReg, DstReg);
2040 if (isMove && SrcReg == DstReg) {
2041 if (li_->hasInterval(SrcReg)) {
2042 LiveInterval &RegInt = li_->getInterval(SrcReg);
2043 // If def of this move instruction is dead, remove its live range
2044 // from the dstination register's live interval.
2045 if (mii->registerDefIsDead(DstReg)) {
2046 if (!ShortenDeadCopySrcLiveRange(RegInt, mii))
2047 ShortenDeadCopyLiveRange(RegInt, mii);
2050 li_->RemoveMachineInstrFromMaps(mii);
2051 mii = mbbi->erase(mii);
2053 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2054 SmallSet<unsigned, 4> UniqueUses;
2055 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
2056 const MachineOperand &mop = mii->getOperand(i);
2057 if (mop.isRegister() && mop.getReg() &&
2058 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2059 unsigned reg = mop.getReg();
2060 // Multiple uses of reg by the same instruction. It should not
2061 // contribute to spill weight again.
2062 if (UniqueUses.count(reg) != 0)
2064 LiveInterval &RegInt = li_->getInterval(reg);
2066 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2067 UniqueUses.insert(reg);
2075 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2076 LiveInterval &LI = I->second;
2077 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2078 // If the live interval length is essentially zero, i.e. in every live
2079 // range the use follows def immediately, it doesn't make sense to spill
2080 // it and hope it will be easier to allocate for this li.
2081 if (isZeroLengthInterval(&LI))
2082 LI.weight = HUGE_VALF;
2084 bool isLoad = false;
2085 if (li_->isReMaterializable(LI, isLoad)) {
2086 // If all of the definitions of the interval are re-materializable,
2087 // it is a preferred candidate for spilling. If non of the defs are
2088 // loads, then it's potentially very cheap to re-materialize.
2089 // FIXME: this gets much more complicated once we support non-trivial
2090 // re-materialization.
2098 // Slightly prefer live interval that has been assigned a preferred reg.
2102 // Divide the weight of the interval by its size. This encourages
2103 // spilling of intervals that are large and have few uses, and
2104 // discourages spilling of small intervals with many uses.
2105 LI.weight /= LI.getSize();
2113 /// print - Implement the dump method.
2114 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2118 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2119 return new SimpleRegisterCoalescing();
2122 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2123 DEFINING_FILE_FOR(SimpleRegisterCoalescing)