1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/OwningPtr.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
42 STATISTIC(numJoins , "Number of interval joins performed");
43 STATISTIC(numCrossRCs , "Number of cross class joins performed");
44 STATISTIC(numCommutes , "Number of instruction commuting performed");
45 STATISTIC(numExtends , "Number of copies extended");
46 STATISTIC(NumReMats , "Number of instructions re-materialized");
47 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
48 STATISTIC(numAborts , "Number of times interval joining aborted");
49 STATISTIC(numDeadValNo, "Number of valno def marked dead");
51 char SimpleRegisterCoalescing::ID = 0;
53 EnableJoining("join-liveintervals",
54 cl::desc("Coalesce copies (default=true)"),
58 DisableCrossClassJoin("disable-cross-class-join",
59 cl::desc("Avoid coalescing cross register class copies"),
60 cl::init(false), cl::Hidden);
62 static RegisterPass<SimpleRegisterCoalescing>
63 X("simple-register-coalescing", "Simple Register Coalescing");
65 // Declare that we implement the RegisterCoalescer interface
66 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
68 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
70 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequired<AliasAnalysis>();
73 AU.addRequired<LiveIntervals>();
74 AU.addPreserved<LiveIntervals>();
75 AU.addPreserved<SlotIndexes>();
76 AU.addRequired<MachineLoopInfo>();
77 AU.addPreserved<MachineLoopInfo>();
78 AU.addPreservedID(MachineDominatorsID);
80 AU.addPreservedID(StrongPHIEliminationID);
82 AU.addPreservedID(PHIEliminationID);
83 AU.addPreservedID(TwoAddressInstructionPassID);
84 MachineFunctionPass::getAnalysisUsage(AU);
87 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
88 /// being the source and IntB being the dest, thus this defines a value number
89 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
90 /// see if we can merge these two pieces of B into a single value number,
91 /// eliminating a copy. For example:
95 /// B1 = A3 <- this copy
97 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
98 /// value number to be replaced with B0 (which simplifies the B liveinterval).
100 /// This returns true if an interval was modified.
102 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
103 MachineInstr *CopyMI) {
104 // Bail if there is no dst interval - can happen when merging physical subreg
106 if (!li_->hasInterval(CP.getDstReg()))
110 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
112 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
113 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
115 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
116 // the example above.
117 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
118 if (BLR == IntB.end()) return false;
119 VNInfo *BValNo = BLR->valno;
121 // Get the location that B is defined at. Two options: either this value has
122 // an unknown definition point or it is defined at CopyIdx. If unknown, we
124 if (!BValNo->getCopy()) return false;
125 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
127 // AValNo is the value number in A that defines the copy, A3 in the example.
128 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
129 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
130 // The live range might not exist after fun with physreg coalescing.
131 if (ALR == IntA.end()) return false;
132 VNInfo *AValNo = ALR->valno;
133 // If it's re-defined by an early clobber somewhere in the live range, then
134 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
136 // 172 %ECX<def> = MOV32rr %reg1039<kill>
137 // 180 INLINEASM <es:subl $5,$1
138 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
140 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
141 // 188 %EAX<def> = MOV32rr %EAX<kill>
142 // 196 %ECX<def> = MOV32rr %ECX<kill>
143 // 204 %ECX<def> = MOV32rr %ECX<kill>
144 // 212 %EAX<def> = MOV32rr %EAX<kill>
145 // 220 %EAX<def> = MOV32rr %EAX
146 // 228 %reg1039<def> = MOV32rr %ECX<kill>
147 // The early clobber operand ties ECX input to the ECX def.
149 // The live interval of ECX is represented as this:
150 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
151 // The coalescer has no idea there was a def in the middle of [174,230].
152 if (AValNo->hasRedefByEC())
155 // If AValNo is defined as a copy from IntB, we can potentially process this.
156 // Get the instruction that defines this value number.
157 if (!CP.isCoalescable(AValNo->getCopy()))
160 // Get the LiveRange in IntB that this value number starts with.
161 LiveInterval::iterator ValLR =
162 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
163 if (ValLR == IntB.end())
166 // Make sure that the end of the live range is inside the same block as
168 MachineInstr *ValLREndInst =
169 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
170 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
173 // Okay, we now know that ValLR ends in the same block that the CopyMI
174 // live-range starts. If there are no intervening live ranges between them in
175 // IntB, we can merge them.
176 if (ValLR+1 != BLR) return false;
178 // If a live interval is a physical register, conservatively check if any
179 // of its sub-registers is overlapping the live interval of the virtual
180 // register. If so, do not coalesce.
181 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
182 *tri_->getSubRegisters(IntB.reg)) {
183 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
184 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
186 dbgs() << "\t\tInterfere with sub-register ";
187 li_->getInterval(*SR).print(dbgs(), tri_);
194 dbgs() << "Extending: ";
195 IntB.print(dbgs(), tri_);
198 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
199 // We are about to delete CopyMI, so need to remove it as the 'instruction
200 // that defines this value #'. Update the valnum with the new defining
202 BValNo->def = FillerStart;
205 // Okay, we can merge them. We need to insert a new liverange:
206 // [ValLR.end, BLR.begin) of either value number, then we merge the
207 // two value numbers.
208 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
210 // If the IntB live range is assigned to a physical register, and if that
211 // physreg has sub-registers, update their live intervals as well.
212 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
213 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
214 LiveInterval &SRLI = li_->getInterval(*SR);
215 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
216 SRLI.getNextValue(FillerStart, 0, true,
217 li_->getVNInfoAllocator())));
221 // Okay, merge "B1" into the same value number as "B0".
222 if (BValNo != ValLR->valno) {
223 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
226 dbgs() << " result = ";
227 IntB.print(dbgs(), tri_);
231 // If the source instruction was killing the source register before the
232 // merge, unset the isKill marker given the live range has been extended.
233 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
235 ValLREndInst->getOperand(UIdx).setIsKill(false);
238 // If the copy instruction was killing the destination register before the
239 // merge, find the last use and trim the live range. That will also add the
241 if (ALR->end == CopyIdx)
242 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
248 /// HasOtherReachingDefs - Return true if there are definitions of IntB
249 /// other than BValNo val# that can reach uses of AValno val# of IntA.
250 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
254 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
256 if (AI->valno != AValNo) continue;
257 LiveInterval::Ranges::iterator BI =
258 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
259 if (BI != IntB.ranges.begin())
261 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
262 if (BI->valno == BValNo)
264 // When BValNo is null, we're looking for a dummy clobber-value for a subreg.
265 if (!BValNo && !BI->valno->isDefAccurate() && !BI->valno->getCopy())
267 if (BI->start <= AI->start && BI->end > AI->start)
269 if (BI->start > AI->start && BI->start < AI->end)
277 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
278 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
280 MachineOperand &MO = MI->getOperand(i);
281 if (MO.isReg() && MO.isImplicit())
282 NewMI->addOperand(MO);
286 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
287 /// IntA being the source and IntB being the dest, thus this defines a value
288 /// number in IntB. If the source value number (in IntA) is defined by a
289 /// commutable instruction and its other operand is coalesced to the copy dest
290 /// register, see if we can transform the copy into a noop by commuting the
291 /// definition. For example,
293 /// A3 = op A2 B0<kill>
295 /// B1 = A3 <- this copy
297 /// = op A3 <- more uses
301 /// B2 = op B0 A2<kill>
303 /// B1 = B2 <- now an identify copy
305 /// = op B2 <- more uses
307 /// This returns true if an interval was modified.
309 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
310 MachineInstr *CopyMI) {
311 // FIXME: For now, only eliminate the copy by commuting its def when the
312 // source register is a virtual register. We want to guard against cases
313 // where the copy is a back edge copy and commuting the def lengthen the
314 // live interval of the source register to the entire loop.
315 if (CP.isPhys() && CP.isFlipped())
318 // Bail if there is no dst interval.
319 if (!li_->hasInterval(CP.getDstReg()))
323 li_->getInstructionIndex(CopyMI).getDefIndex();
326 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
328 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
330 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
331 // the example above.
332 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
333 if (BLR == IntB.end()) return false;
334 VNInfo *BValNo = BLR->valno;
336 // Get the location that B is defined at. Two options: either this value has
337 // an unknown definition point or it is defined at CopyIdx. If unknown, we
339 if (!BValNo->getCopy()) return false;
340 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
342 // AValNo is the value number in A that defines the copy, A3 in the example.
343 LiveInterval::iterator ALR =
344 IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); //
346 assert(ALR != IntA.end() && "Live range not found!");
347 VNInfo *AValNo = ALR->valno;
348 // If other defs can reach uses of this def, then it's not safe to perform
349 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
351 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
352 AValNo->isUnused() || AValNo->hasPHIKill())
354 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
357 const TargetInstrDesc &TID = DefMI->getDesc();
358 if (!TID.isCommutable())
360 // If DefMI is a two-address instruction then commuting it will change the
361 // destination register.
362 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
363 assert(DefIdx != -1);
365 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
367 unsigned Op1, Op2, NewDstIdx;
368 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
372 else if (Op2 == UseOpIdx)
377 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
378 unsigned NewReg = NewDstMO.getReg();
379 if (NewReg != IntB.reg || !NewDstMO.isKill())
382 // Make sure there are no other definitions of IntB that would reach the
383 // uses which the new definition can reach.
384 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
387 bool BHasSubRegs = false;
388 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
389 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
391 // Abort if the subregisters of IntB.reg have values that are not simply the
392 // clobbers from the superreg.
394 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
395 if (HasOtherReachingDefs(IntA, li_->getInterval(*SR), AValNo, 0))
398 // If some of the uses of IntA.reg is already coalesced away, return false.
399 // It's not possible to determine whether it's safe to perform the coalescing.
400 for (MachineRegisterInfo::use_nodbg_iterator UI =
401 mri_->use_nodbg_begin(IntA.reg),
402 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
403 MachineInstr *UseMI = &*UI;
404 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
405 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
406 if (ULR == IntA.end())
408 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
412 // At this point we have decided that it is legal to do this
413 // transformation. Start by commuting the instruction.
414 MachineBasicBlock *MBB = DefMI->getParent();
415 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
418 if (NewMI != DefMI) {
419 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
420 MBB->insert(DefMI, NewMI);
423 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
424 NewMI->getOperand(OpIdx).setIsKill();
426 bool BHasPHIKill = BValNo->hasPHIKill();
427 SmallVector<VNInfo*, 4> BDeadValNos;
428 std::map<SlotIndex, SlotIndex> BExtend;
430 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
438 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
440 BExtend[ALR->end] = BLR->end;
442 // Update uses of IntA of the specific Val# with IntB.
443 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
444 UE = mri_->use_end(); UI != UE;) {
445 MachineOperand &UseMO = UI.getOperand();
446 MachineInstr *UseMI = &*UI;
448 if (JoinedCopies.count(UseMI))
450 if (UseMI->isDebugValue()) {
451 // FIXME These don't have an instruction index. Not clear we have enough
452 // info to decide whether to do this replacement or not. For now do it.
453 UseMO.setReg(NewReg);
456 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
457 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
458 if (ULR == IntA.end() || ULR->valno != AValNo)
460 UseMO.setReg(NewReg);
463 if (UseMO.isKill()) {
465 UseMO.setIsKill(false);
467 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
468 if (UseMI->isCopy()) {
469 if (UseMI->getOperand(0).getReg() != IntB.reg ||
470 UseMI->getOperand(0).getSubReg())
472 } else if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
473 if (DstReg != IntB.reg || DstSubIdx)
477 // This copy will become a noop. If it's defining a new val#,
478 // remove that val# as well. However this live range is being
479 // extended to the end of the existing live range defined by the copy.
480 SlotIndex DefIdx = UseIdx.getDefIndex();
481 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
482 BHasPHIKill |= DLR->valno->hasPHIKill();
483 assert(DLR->valno->def == DefIdx);
484 BDeadValNos.push_back(DLR->valno);
485 BExtend[DLR->start] = DLR->end;
486 JoinedCopies.insert(UseMI);
489 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
490 // simply extend BLR if CopyMI doesn't end the range.
492 dbgs() << "Extending: ";
493 IntB.print(dbgs(), tri_);
496 // Remove val#'s defined by copies that will be coalesced away.
497 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
498 VNInfo *DeadVNI = BDeadValNos[i];
500 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
501 LiveInterval &SRLI = li_->getInterval(*SR);
502 if (const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def))
503 SRLI.removeValNo(SRLR->valno);
506 IntB.removeValNo(BDeadValNos[i]);
509 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
511 VNInfo *ValNo = BValNo;
512 ValNo->def = AValNo->def;
514 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
516 if (AI->valno != AValNo) continue;
517 SlotIndex End = AI->end;
518 std::map<SlotIndex, SlotIndex>::iterator
519 EI = BExtend.find(End);
520 if (EI != BExtend.end())
522 IntB.addRange(LiveRange(AI->start, End, ValNo));
524 ValNo->setHasPHIKill(BHasPHIKill);
527 dbgs() << " result = ";
528 IntB.print(dbgs(), tri_);
529 dbgs() << "\nShortening: ";
530 IntA.print(dbgs(), tri_);
533 IntA.removeValNo(AValNo);
536 dbgs() << " result = ";
537 IntA.print(dbgs(), tri_);
545 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
546 /// fallthoughs to SuccMBB.
547 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
548 MachineBasicBlock *SuccMBB,
549 const TargetInstrInfo *tii_) {
552 MachineBasicBlock *TBB = 0, *FBB = 0;
553 SmallVector<MachineOperand, 4> Cond;
554 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
555 MBB->isSuccessor(SuccMBB);
558 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
559 /// from a physical register live interval as well as from the live intervals
560 /// of its sub-registers.
561 static void removeRange(LiveInterval &li,
562 SlotIndex Start, SlotIndex End,
563 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
564 li.removeRange(Start, End, true);
565 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
566 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
567 if (!li_->hasInterval(*SR))
569 LiveInterval &sli = li_->getInterval(*SR);
570 SlotIndex RemoveStart = Start;
571 SlotIndex RemoveEnd = Start;
573 while (RemoveEnd != End) {
574 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
577 RemoveEnd = (LR->end < End) ? LR->end : End;
578 sli.removeRange(RemoveStart, RemoveEnd, true);
579 RemoveStart = RemoveEnd;
585 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
586 /// as the copy instruction, trim the live interval to the last use and return
589 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
590 MachineBasicBlock *CopyMBB,
592 const LiveRange *LR) {
593 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
594 SlotIndex LastUseIdx;
595 MachineOperand *LastUse =
596 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
598 MachineInstr *LastUseMI = LastUse->getParent();
599 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
606 // r1025<dead> = r1024<kill>
607 if (MBBStart < LR->end)
608 removeRange(li, MBBStart, LR->end, li_, tri_);
612 // There are uses before the copy, just shorten the live range to the end
614 LastUse->setIsKill();
615 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
616 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
617 if ((LastUseMI->isCopy() && !LastUseMI->getOperand(0).getSubReg()) ||
618 (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
619 DstReg == li.reg && DstSubIdx == 0)) {
620 // Last use is itself an identity code.
621 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg,
623 LastUseMI->getOperand(DeadIdx).setIsDead();
629 if (LR->start <= MBBStart && LR->end > MBBStart) {
630 if (LR->start == li_->getZeroIndex()) {
631 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
632 // Live-in to the function but dead. Remove it from entry live-in set.
633 mf_->begin()->removeLiveIn(li.reg);
635 // FIXME: Shorten intervals in BBs that reaches this BB.
641 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
642 /// computation, replace the copy by rematerialize the definition.
643 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
646 MachineInstr *CopyMI) {
647 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
648 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
649 assert(SrcLR != SrcInt.end() && "Live range not found!");
650 VNInfo *ValNo = SrcLR->valno;
651 // If other defs can reach uses of this def, then it's not safe to perform
652 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
654 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
655 ValNo->isUnused() || ValNo->hasPHIKill())
657 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
658 assert(DefMI && "Defining instruction disappeared");
659 const TargetInstrDesc &TID = DefMI->getDesc();
660 if (!TID.isAsCheapAsAMove())
662 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
664 bool SawStore = false;
665 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
667 if (TID.getNumDefs() != 1)
669 if (!DefMI->isImplicitDef()) {
670 // Make sure the copy destination register class fits the instruction
671 // definition register class. The mismatch can happen as a result of earlier
672 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
673 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
674 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
675 if (mri_->getRegClass(DstReg) != RC)
677 } else if (!RC->contains(DstReg))
681 // If destination register has a sub-register index on it, make sure it mtches
682 // the instruction register class.
684 const TargetInstrDesc &TID = DefMI->getDesc();
685 if (TID.getNumDefs() != 1)
687 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
688 const TargetRegisterClass *DstSubRC =
689 DstRC->getSubRegisterRegClass(DstSubIdx);
690 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
693 else if (DefRC != DstSubRC)
697 RemoveCopyFlag(DstReg, CopyMI);
699 // If copy kills the source register, find the last use and propagate
701 bool checkForDeadDef = false;
702 MachineBasicBlock *MBB = CopyMI->getParent();
703 if (SrcLR->end == CopyIdx.getDefIndex())
704 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
705 checkForDeadDef = true;
708 MachineBasicBlock::iterator MII =
709 llvm::next(MachineBasicBlock::iterator(CopyMI));
710 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
711 MachineInstr *NewMI = prior(MII);
713 if (checkForDeadDef) {
714 // PR4090 fix: Trim interval failed because there was no use of the
715 // source interval in this MBB. If the def is in this MBB too then we
716 // should mark it dead:
717 if (DefMI->getParent() == MBB) {
718 DefMI->addRegisterDead(SrcInt.reg, tri_);
719 SrcLR->end = SrcLR->start.getNextSlot();
723 // CopyMI may have implicit operands, transfer them over to the newly
724 // rematerialized instruction. And update implicit def interval valnos.
725 for (unsigned i = CopyMI->getDesc().getNumOperands(),
726 e = CopyMI->getNumOperands(); i != e; ++i) {
727 MachineOperand &MO = CopyMI->getOperand(i);
728 if (MO.isReg() && MO.isImplicit())
729 NewMI->addOperand(MO);
731 RemoveCopyFlag(MO.getReg(), CopyMI);
734 TransferImplicitOps(CopyMI, NewMI);
735 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
736 CopyMI->eraseFromParent();
737 ReMatCopies.insert(CopyMI);
738 ReMatDefs.insert(DefMI);
739 DEBUG(dbgs() << "Remat: " << *NewMI);
744 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
745 /// update the subregister number if it is not zero. If DstReg is a
746 /// physical register and the existing subregister number of the def / use
747 /// being updated is not zero, make sure to set it to the correct physical
750 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
751 bool DstIsPhys = CP.isPhys();
752 unsigned SrcReg = CP.getSrcReg();
753 unsigned DstReg = CP.getDstReg();
754 unsigned SubIdx = CP.getSubIdx();
756 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
757 MachineInstr *UseMI = I.skipInstruction();) {
758 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
761 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
762 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
763 CopySrcSubIdx, CopyDstSubIdx) &&
764 CopySrcSubIdx == 0 && CopyDstSubIdx == 0 &&
765 CopySrcReg != CopyDstReg && CopySrcReg == SrcReg &&
766 CopyDstReg != DstReg && !JoinedCopies.count(UseMI) &&
767 ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg, 0,
772 SmallVector<unsigned,8> Ops;
774 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
775 bool Kills = false, Deads = false;
777 // Replace SrcReg with DstReg in all UseMI operands.
778 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
779 MachineOperand &MO = UseMI->getOperand(Ops[i]);
780 Kills |= MO.isKill();
781 Deads |= MO.isDead();
784 MO.substPhysReg(DstReg, *tri_);
786 MO.substVirtReg(DstReg, SubIdx, *tri_);
789 // This instruction is a copy that will be removed.
790 if (JoinedCopies.count(UseMI))
794 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
795 // read-modify-write of DstReg.
797 UseMI->addRegisterDead(DstReg, tri_);
798 else if (!Reads && Writes)
799 UseMI->addRegisterDefined(DstReg, tri_);
801 // Kill flags apply to the whole physical register.
802 if (DstIsPhys && Kills)
803 UseMI->addRegisterKilled(DstReg, tri_);
807 dbgs() << "\t\tupdated: ";
808 if (!UseMI->isDebugValue())
809 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
814 // After updating the operand, check if the machine instruction has
815 // become a copy. If so, update its val# information.
816 const TargetInstrDesc &TID = UseMI->getDesc();
817 if (DstIsPhys || TID.getNumDefs() != 1 || TID.getNumOperands() <= 2)
820 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
821 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
822 CopySrcSubIdx, CopyDstSubIdx) &&
823 CopySrcReg != CopyDstReg &&
824 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
825 allocatableRegs_[CopyDstReg])) {
826 LiveInterval &LI = li_->getInterval(CopyDstReg);
828 li_->getInstructionIndex(UseMI).getDefIndex();
829 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
830 if (DLR->valno->def == DefIdx)
831 DLR->valno->setCopy(UseMI);
837 /// removeIntervalIfEmpty - Check if the live interval of a physical register
838 /// is empty, if so remove it and also remove the empty intervals of its
839 /// sub-registers. Return true if live interval is removed.
840 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
841 const TargetRegisterInfo *tri_) {
843 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
844 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
845 if (!li_->hasInterval(*SR))
847 LiveInterval &sli = li_->getInterval(*SR);
849 li_->removeInterval(*SR);
851 li_->removeInterval(li.reg);
857 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
858 /// Return true if live interval is removed.
859 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
860 MachineInstr *CopyMI) {
861 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
862 LiveInterval::iterator MLR =
863 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
865 return false; // Already removed by ShortenDeadCopySrcLiveRange.
866 SlotIndex RemoveStart = MLR->start;
867 SlotIndex RemoveEnd = MLR->end;
868 SlotIndex DefIdx = CopyIdx.getDefIndex();
869 // Remove the liverange that's defined by this.
870 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
871 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
872 return removeIntervalIfEmpty(li, li_, tri_);
877 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
878 /// the val# it defines. If the live interval becomes empty, remove it as well.
879 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
880 MachineInstr *DefMI) {
881 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
882 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
883 if (DefIdx != MLR->valno->def)
885 li.removeValNo(MLR->valno);
886 return removeIntervalIfEmpty(li, li_, tri_);
889 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
890 const MachineInstr *CopyMI) {
891 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
892 if (li_->hasInterval(DstReg)) {
893 LiveInterval &LI = li_->getInterval(DstReg);
894 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
895 if (LR->valno->getCopy() == CopyMI)
896 LR->valno->setCopy(0);
898 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
900 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
901 if (!li_->hasInterval(*AS))
903 LiveInterval &LI = li_->getInterval(*AS);
904 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
905 if (LR->valno->getCopy() == CopyMI)
906 LR->valno->setCopy(0);
910 /// PropagateDeadness - Propagate the dead marker to the instruction which
911 /// defines the val#.
912 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
913 SlotIndex &LRStart, LiveIntervals *li_,
914 const TargetRegisterInfo* tri_) {
915 MachineInstr *DefMI =
916 li_->getInstructionFromIndex(LRStart.getDefIndex());
917 if (DefMI && DefMI != CopyMI) {
918 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
920 DefMI->getOperand(DeadIdx).setIsDead();
922 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
923 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
924 LRStart = LRStart.getNextSlot();
928 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
929 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
930 /// ends the live range there. If there isn't another use, then this live range
931 /// is dead. Return true if live interval is removed.
933 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
934 MachineInstr *CopyMI) {
935 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
936 if (CopyIdx == SlotIndex()) {
937 // FIXME: special case: function live in. It can be a general case if the
938 // first instruction index starts at > 0 value.
939 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
940 // Live-in to the function but dead. Remove it from entry live-in set.
941 if (mf_->begin()->isLiveIn(li.reg))
942 mf_->begin()->removeLiveIn(li.reg);
943 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
944 removeRange(li, LR->start, LR->end, li_, tri_);
945 return removeIntervalIfEmpty(li, li_, tri_);
948 LiveInterval::iterator LR =
949 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
951 // Livein but defined by a phi.
954 SlotIndex RemoveStart = LR->start;
955 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
956 if (LR->end > RemoveEnd)
957 // More uses past this copy? Nothing to do.
960 // If there is a last use in the same bb, we can't remove the live range.
961 // Shorten the live interval and return.
962 MachineBasicBlock *CopyMBB = CopyMI->getParent();
963 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
966 // There are other kills of the val#. Nothing to do.
967 if (!li.isOnlyLROfValNo(LR))
970 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
971 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
972 // If the live range starts in another mbb and the copy mbb is not a fall
973 // through mbb, then we can only cut the range from the beginning of the
975 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
977 if (LR->valno->def == RemoveStart) {
978 // If the def MI defines the val# and this copy is the only kill of the
979 // val#, then propagate the dead marker.
980 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
984 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
985 return removeIntervalIfEmpty(li, li_, tri_);
989 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
990 /// two virtual registers from different register classes.
992 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
994 const TargetRegisterClass *SrcRC,
995 const TargetRegisterClass *DstRC,
996 const TargetRegisterClass *NewRC) {
997 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
998 // This heuristics is good enough in practice, but it's obviously not *right*.
999 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
1000 // out all but the most restrictive register classes.
1001 if (NewRCCount > 4 ||
1002 // Early exit if the function is fairly small, coalesce aggressively if
1003 // that's the case. For really special register classes with 3 or
1004 // fewer registers, be a bit more careful.
1005 (li_->getFuncInstructionCount() / NewRCCount) < 8)
1007 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1008 LiveInterval &DstInt = li_->getInterval(DstReg);
1009 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
1010 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
1011 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
1013 // Estimate *register use density*. If it doubles or more, abort.
1014 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
1015 mri_->use_nodbg_end());
1016 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
1017 mri_->use_nodbg_end());
1018 unsigned NewUses = SrcUses + DstUses;
1019 unsigned NewSize = SrcSize + DstSize;
1020 if (SrcRC != NewRC && SrcSize > NewRCCount) {
1021 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1022 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1025 if (DstRC != NewRC && DstSize > NewRCCount) {
1026 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1027 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1034 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1035 /// which are the src/dst of the copy instruction CopyMI. This returns true
1036 /// if the copy was successfully coalesced away. If it is not currently
1037 /// possible to coalesce this interval, but it may be possible if other
1038 /// things get coalesced, then it returns true by reference in 'Again'.
1039 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1040 MachineInstr *CopyMI = TheCopy.MI;
1043 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1044 return false; // Already done.
1046 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1048 CoalescerPair CP(*tii_, *tri_);
1049 if (!CP.setRegisters(CopyMI)) {
1050 DEBUG(dbgs() << "\tNot coalescable.\n");
1054 // If they are already joined we continue.
1055 if (CP.getSrcReg() == CP.getDstReg()) {
1056 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1057 return false; // Not coalescable.
1060 DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
1062 // Enforce policies.
1064 DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
1065 // Only coalesce to allocatable physreg.
1066 if (!allocatableRegs_[CP.getDstReg()]) {
1067 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1068 return false; // Not coalescable.
1072 dbgs() << " with reg%" << CP.getDstReg();
1074 dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1075 dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1078 // Avoid constraining virtual register regclass too much.
1079 if (CP.isCrossClass()) {
1080 if (DisableCrossClassJoin) {
1081 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1084 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1085 mri_->getRegClass(CP.getSrcReg()),
1086 mri_->getRegClass(CP.getDstReg()),
1088 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1089 << CP.getNewRC()->getName() << ".\n");
1090 Again = true; // May be possible to coalesce later.
1095 // When possible, let DstReg be the larger interval.
1096 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1097 li_->getInterval(CP.getDstReg()).ranges.size())
1101 // We need to be careful about coalescing a source physical register with a
1102 // virtual register. Once the coalescing is done, it cannot be broken and
1103 // these are not spillable! If the destination interval uses are far away,
1104 // think twice about coalescing them!
1105 // FIXME: Why are we skipping this test for partial copies?
1106 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1107 if (!CP.isPartial() && CP.isPhys()) {
1108 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1110 // Don't join with physregs that have a ridiculous number of live
1111 // ranges. The data structure performance is really bad when that
1113 if (li_->hasInterval(CP.getDstReg()) &&
1114 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1115 mri_->setRegAllocationHint(CP.getSrcReg(), 0, CP.getDstReg());
1118 << "\tPhysical register live interval too complicated, abort!\n");
1122 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1123 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1124 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1125 if (Length > Threshold &&
1126 std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1127 mri_->use_nodbg_end()) * Threshold < Length) {
1128 // Before giving up coalescing, if definition of source is defined by
1129 // trivial computation, try rematerializing it.
1130 if (!CP.isFlipped() &&
1131 ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1134 mri_->setRegAllocationHint(CP.getSrcReg(), 0, CP.getDstReg());
1136 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1137 Again = true; // May be possible to coalesce later.
1142 // Okay, attempt to join these two intervals. On failure, this returns false.
1143 // Otherwise, if one of the intervals being joined is a physreg, this method
1144 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1145 // been modified, so we can use this information below to update aliases.
1146 if (!JoinIntervals(CP)) {
1147 // Coalescing failed.
1149 // If definition of source is defined by trivial computation, try
1150 // rematerializing it.
1151 if (!CP.isFlipped() &&
1152 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1153 CP.getDstReg(), 0, CopyMI))
1156 // If we can eliminate the copy without merging the live ranges, do so now.
1157 if (!CP.isPartial()) {
1158 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1159 RemoveCopyByCommutingDef(CP, CopyMI)) {
1160 JoinedCopies.insert(CopyMI);
1161 DEBUG(dbgs() << "\tTrivial!\n");
1166 // Otherwise, we are unable to join the intervals.
1167 DEBUG(dbgs() << "\tInterference!\n");
1168 Again = true; // May be possible to coalesce later.
1172 // Coalescing to a virtual register that is of a sub-register class of the
1173 // other. Make sure the resulting register is set to the right register class.
1174 if (CP.isCrossClass()) {
1176 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1179 // Remember to delete the copy instruction.
1180 JoinedCopies.insert(CopyMI);
1182 UpdateRegDefsUses(CP);
1184 // If we have extended the live range of a physical register, make sure we
1185 // update live-in lists as well.
1187 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1188 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1189 // ranges for this, and they are preserved.
1190 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1191 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1193 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1194 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1195 MachineBasicBlock &block = *BlockSeq[idx];
1196 if (!block.isLiveIn(CP.getDstReg()))
1197 block.addLiveIn(CP.getDstReg());
1203 // SrcReg is guarateed to be the register whose live interval that is
1205 li_->removeInterval(CP.getSrcReg());
1207 // Update regalloc hint.
1208 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1211 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1212 dbgs() << "\tJoined. Result = ";
1213 DstInt.print(dbgs(), tri_);
1221 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1222 /// compute what the resultant value numbers for each value in the input two
1223 /// ranges will be. This is complicated by copies between the two which can
1224 /// and will commonly cause multiple value numbers to be merged into one.
1226 /// VN is the value number that we're trying to resolve. InstDefiningValue
1227 /// keeps track of the new InstDefiningValue assignment for the result
1228 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1229 /// whether a value in this or other is a copy from the opposite set.
1230 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1231 /// already been assigned.
1233 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1234 /// contains the value number the copy is from.
1236 static unsigned ComputeUltimateVN(VNInfo *VNI,
1237 SmallVector<VNInfo*, 16> &NewVNInfo,
1238 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1239 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1240 SmallVector<int, 16> &ThisValNoAssignments,
1241 SmallVector<int, 16> &OtherValNoAssignments) {
1242 unsigned VN = VNI->id;
1244 // If the VN has already been computed, just return it.
1245 if (ThisValNoAssignments[VN] >= 0)
1246 return ThisValNoAssignments[VN];
1247 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1249 // If this val is not a copy from the other val, then it must be a new value
1250 // number in the destination.
1251 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1252 if (I == ThisFromOther.end()) {
1253 NewVNInfo.push_back(VNI);
1254 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1256 VNInfo *OtherValNo = I->second;
1258 // Otherwise, this *is* a copy from the RHS. If the other side has already
1259 // been computed, return it.
1260 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1261 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1263 // Mark this value number as currently being computed, then ask what the
1264 // ultimate value # of the other value is.
1265 ThisValNoAssignments[VN] = -2;
1266 unsigned UltimateVN =
1267 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1268 OtherValNoAssignments, ThisValNoAssignments);
1269 return ThisValNoAssignments[VN] = UltimateVN;
1272 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1274 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1275 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1276 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1278 // If a live interval is a physical register, check for interference with any
1279 // aliases. The interference check implemented here is a bit more conservative
1280 // than the full interfeence check below. We allow overlapping live ranges
1281 // only when one is a copy of the other.
1283 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1284 if (!li_->hasInterval(*AS))
1286 const LiveInterval &LHS = li_->getInterval(*AS);
1287 LiveInterval::const_iterator LI = LHS.begin();
1288 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1290 LI = std::lower_bound(LI, LHS.end(), RI->start);
1291 // Does LHS have an overlapping live range starting before RI?
1292 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1293 (RI->start != RI->valno->def ||
1294 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1296 dbgs() << "\t\tInterference from alias: ";
1297 LHS.print(dbgs(), tri_);
1298 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1303 // Check that LHS ranges beginning in this range are copies.
1304 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1305 if (LI->start != LI->valno->def ||
1306 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1308 dbgs() << "\t\tInterference from alias: ";
1309 LHS.print(dbgs(), tri_);
1310 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1319 // Compute the final value assignment, assuming that the live ranges can be
1321 SmallVector<int, 16> LHSValNoAssignments;
1322 SmallVector<int, 16> RHSValNoAssignments;
1323 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1324 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1325 SmallVector<VNInfo*, 16> NewVNInfo;
1327 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1328 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1330 // Loop over the value numbers of the LHS, seeing if any are defined from
1332 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1335 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
1338 // Never join with a register that has EarlyClobber redefs.
1339 if (VNI->hasRedefByEC())
1342 // DstReg is known to be a register in the LHS interval. If the src is
1343 // from the RHS interval, we can use its value #.
1344 if (!CP.isCoalescable(VNI->getCopy()))
1347 // Figure out the value # from the RHS.
1348 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1349 // The copy could be to an aliased physreg.
1351 LHSValsDefinedFromRHS[VNI] = lr->valno;
1354 // Loop over the value numbers of the RHS, seeing if any are defined from
1356 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1359 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
1362 // Never join with a register that has EarlyClobber redefs.
1363 if (VNI->hasRedefByEC())
1366 // DstReg is known to be a register in the RHS interval. If the src is
1367 // from the LHS interval, we can use its value #.
1368 if (!CP.isCoalescable(VNI->getCopy()))
1371 // Figure out the value # from the LHS.
1372 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1373 // The copy could be to an aliased physreg.
1375 RHSValsDefinedFromLHS[VNI] = lr->valno;
1378 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1379 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1380 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1382 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1385 unsigned VN = VNI->id;
1386 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1388 ComputeUltimateVN(VNI, NewVNInfo,
1389 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1390 LHSValNoAssignments, RHSValNoAssignments);
1392 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1395 unsigned VN = VNI->id;
1396 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1398 // If this value number isn't a copy from the LHS, it's a new number.
1399 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1400 NewVNInfo.push_back(VNI);
1401 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1405 ComputeUltimateVN(VNI, NewVNInfo,
1406 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1407 RHSValNoAssignments, LHSValNoAssignments);
1410 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1411 // interval lists to see if these intervals are coalescable.
1412 LiveInterval::const_iterator I = LHS.begin();
1413 LiveInterval::const_iterator IE = LHS.end();
1414 LiveInterval::const_iterator J = RHS.begin();
1415 LiveInterval::const_iterator JE = RHS.end();
1417 // Skip ahead until the first place of potential sharing.
1418 if (I != IE && J != JE) {
1419 if (I->start < J->start) {
1420 I = std::upper_bound(I, IE, J->start);
1421 if (I != LHS.begin()) --I;
1422 } else if (J->start < I->start) {
1423 J = std::upper_bound(J, JE, I->start);
1424 if (J != RHS.begin()) --J;
1428 while (I != IE && J != JE) {
1429 // Determine if these two live ranges overlap.
1431 if (I->start < J->start) {
1432 Overlaps = I->end > J->start;
1434 Overlaps = J->end > I->start;
1437 // If so, check value # info to determine if they are really different.
1439 // If the live range overlap will map to the same value number in the
1440 // result liverange, we can still coalesce them. If not, we can't.
1441 if (LHSValNoAssignments[I->valno->id] !=
1442 RHSValNoAssignments[J->valno->id])
1444 // If it's re-defined by an early clobber somewhere in the live range,
1445 // then conservatively abort coalescing.
1446 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1450 if (I->end < J->end)
1456 // Update kill info. Some live ranges are extended due to copy coalescing.
1457 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1458 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1459 VNInfo *VNI = I->first;
1460 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1461 if (VNI->hasPHIKill())
1462 NewVNInfo[LHSValID]->setHasPHIKill(true);
1465 // Update kill info. Some live ranges are extended due to copy coalescing.
1466 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1467 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1468 VNInfo *VNI = I->first;
1469 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1470 if (VNI->hasPHIKill())
1471 NewVNInfo[RHSValID]->setHasPHIKill(true);
1474 if (LHSValNoAssignments.empty())
1475 LHSValNoAssignments.push_back(-1);
1476 if (RHSValNoAssignments.empty())
1477 RHSValNoAssignments.push_back(-1);
1479 // If we get here, we know that we can coalesce the live ranges. Ask the
1480 // intervals to coalesce themselves now.
1481 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1487 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1488 // depth of the basic block (the unsigned), and then on the MBB number.
1489 struct DepthMBBCompare {
1490 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1491 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1492 // Deeper loops first
1493 if (LHS.first != RHS.first)
1494 return LHS.first > RHS.first;
1496 // Prefer blocks that are more connected in the CFG. This takes care of
1497 // the most difficult copies first while intervals are short.
1498 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1499 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1503 // As a last resort, sort by block number.
1504 return LHS.second->getNumber() < RHS.second->getNumber();
1509 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1510 std::vector<CopyRec> &TryAgain) {
1511 DEBUG(dbgs() << MBB->getName() << ":\n");
1513 std::vector<CopyRec> VirtCopies;
1514 std::vector<CopyRec> PhysCopies;
1515 std::vector<CopyRec> ImpDefCopies;
1516 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1518 MachineInstr *Inst = MII++;
1520 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1521 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1522 bool isInsUndef = false;
1523 if (Inst->isCopy() || Inst->isExtractSubreg()) {
1524 DstReg = Inst->getOperand(0).getReg();
1525 SrcReg = Inst->getOperand(1).getReg();
1526 } else if (Inst->isSubregToReg()) {
1527 DstReg = Inst->getOperand(0).getReg();
1528 SrcReg = Inst->getOperand(2).getReg();
1529 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1532 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1533 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1535 (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
1536 ImpDefCopies.push_back(CopyRec(Inst, 0));
1537 else if (SrcIsPhys || DstIsPhys)
1538 PhysCopies.push_back(CopyRec(Inst, 0));
1540 VirtCopies.push_back(CopyRec(Inst, 0));
1543 // Try coalescing implicit copies and insert_subreg <undef> first,
1544 // followed by copies to / from physical registers, then finally copies
1545 // from virtual registers to virtual registers.
1546 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1547 CopyRec &TheCopy = ImpDefCopies[i];
1549 if (!JoinCopy(TheCopy, Again))
1551 TryAgain.push_back(TheCopy);
1553 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1554 CopyRec &TheCopy = PhysCopies[i];
1556 if (!JoinCopy(TheCopy, Again))
1558 TryAgain.push_back(TheCopy);
1560 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1561 CopyRec &TheCopy = VirtCopies[i];
1563 if (!JoinCopy(TheCopy, Again))
1565 TryAgain.push_back(TheCopy);
1569 void SimpleRegisterCoalescing::joinIntervals() {
1570 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1572 std::vector<CopyRec> TryAgainList;
1573 if (loopInfo->empty()) {
1574 // If there are no loops in the function, join intervals in function order.
1575 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1577 CopyCoalesceInMBB(I, TryAgainList);
1579 // Otherwise, join intervals in inner loops before other intervals.
1580 // Unfortunately we can't just iterate over loop hierarchy here because
1581 // there may be more MBB's than BB's. Collect MBB's for sorting.
1583 // Join intervals in the function prolog first. We want to join physical
1584 // registers with virtual registers before the intervals got too long.
1585 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1586 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1587 MachineBasicBlock *MBB = I;
1588 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1591 // Sort by loop depth.
1592 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1594 // Finally, join intervals in loop nest order.
1595 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1596 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1599 // Joining intervals can allow other intervals to be joined. Iteratively join
1600 // until we make no progress.
1601 bool ProgressMade = true;
1602 while (ProgressMade) {
1603 ProgressMade = false;
1605 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1606 CopyRec &TheCopy = TryAgainList[i];
1611 bool Success = JoinCopy(TheCopy, Again);
1612 if (Success || !Again) {
1613 TheCopy.MI = 0; // Mark this one as done.
1614 ProgressMade = true;
1620 /// Return true if the two specified registers belong to different register
1621 /// classes. The registers may be either phys or virt regs.
1623 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1624 unsigned RegB) const {
1625 // Get the register classes for the first reg.
1626 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1627 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1628 "Shouldn't consider two physregs!");
1629 return !mri_->getRegClass(RegB)->contains(RegA);
1632 // Compare against the regclass for the second reg.
1633 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1634 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1635 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1636 return RegClassA != RegClassB;
1638 return !RegClassA->contains(RegB);
1641 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1642 /// between cycles Start and End or NULL if there are no uses.
1644 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1647 SlotIndex &UseIdx) const{
1648 UseIdx = SlotIndex();
1649 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1650 MachineOperand *LastUse = NULL;
1651 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1652 E = mri_->use_nodbg_end(); I != E; ++I) {
1653 MachineOperand &Use = I.getOperand();
1654 MachineInstr *UseMI = Use.getParent();
1655 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1656 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1657 SrcReg == DstReg && SrcSubIdx == DstSubIdx)
1658 // Ignore identity copies.
1660 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1661 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1662 // that compares higher than any other interval.
1663 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1665 UseIdx = Idx.getUseIndex();
1671 SlotIndex s = Start;
1672 SlotIndex e = End.getPrevSlot().getBaseIndex();
1674 // Skip deleted instructions
1675 MachineInstr *MI = li_->getInstructionFromIndex(e);
1676 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1677 e = e.getPrevIndex();
1678 MI = li_->getInstructionFromIndex(e);
1680 if (e < s || MI == NULL)
1683 // Ignore identity copies.
1684 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1685 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1686 SrcReg == DstReg && SrcSubIdx == DstSubIdx))
1687 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1688 MachineOperand &Use = MI->getOperand(i);
1689 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1690 tri_->regsOverlap(Use.getReg(), Reg)) {
1691 UseIdx = e.getUseIndex();
1696 e = e.getPrevIndex();
1702 void SimpleRegisterCoalescing::releaseMemory() {
1703 JoinedCopies.clear();
1704 ReMatCopies.clear();
1708 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1710 mri_ = &fn.getRegInfo();
1711 tm_ = &fn.getTarget();
1712 tri_ = tm_->getRegisterInfo();
1713 tii_ = tm_->getInstrInfo();
1714 li_ = &getAnalysis<LiveIntervals>();
1715 AA = &getAnalysis<AliasAnalysis>();
1716 loopInfo = &getAnalysis<MachineLoopInfo>();
1718 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1719 << "********** Function: "
1720 << ((Value*)mf_->getFunction())->getName() << '\n');
1722 allocatableRegs_ = tri_->getAllocatableSet(fn);
1723 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1724 E = tri_->regclass_end(); I != E; ++I)
1725 allocatableRCRegs_.insert(std::make_pair(*I,
1726 tri_->getAllocatableSet(fn, *I)));
1728 // Join (coalesce) intervals if requested.
1729 if (EnableJoining) {
1732 dbgs() << "********** INTERVALS POST JOINING **********\n";
1733 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1735 I->second->print(dbgs(), tri_);
1741 // Perform a final pass over the instructions and compute spill weights
1742 // and remove identity moves.
1743 SmallVector<unsigned, 4> DeadDefs;
1744 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1745 mbbi != mbbe; ++mbbi) {
1746 MachineBasicBlock* mbb = mbbi;
1747 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1749 MachineInstr *MI = mii;
1750 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1751 if (JoinedCopies.count(MI)) {
1752 // Delete all coalesced copies.
1753 bool DoDelete = true;
1754 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1755 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1756 SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1757 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1758 // Do not delete extract_subreg, insert_subreg of physical
1759 // registers unless the definition is dead. e.g.
1760 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1761 // or else the scavenger may complain. LowerSubregs will
1762 // delete them later.
1765 if (MI->allDefsAreDead()) {
1766 LiveInterval &li = li_->getInterval(SrcReg);
1767 if (!ShortenDeadCopySrcLiveRange(li, MI))
1768 ShortenDeadCopyLiveRange(li, MI);
1772 mii = llvm::next(mii);
1774 li_->RemoveMachineInstrFromMaps(MI);
1775 mii = mbbi->erase(mii);
1781 // Now check if this is a remat'ed def instruction which is now dead.
1782 if (ReMatDefs.count(MI)) {
1784 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1785 const MachineOperand &MO = MI->getOperand(i);
1788 unsigned Reg = MO.getReg();
1791 if (TargetRegisterInfo::isVirtualRegister(Reg))
1792 DeadDefs.push_back(Reg);
1795 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1796 !mri_->use_nodbg_empty(Reg)) {
1802 while (!DeadDefs.empty()) {
1803 unsigned DeadDef = DeadDefs.back();
1804 DeadDefs.pop_back();
1805 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1807 li_->RemoveMachineInstrFromMaps(mii);
1808 mii = mbbi->erase(mii);
1814 // If the move will be an identity move delete it
1815 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1816 if (isMove && SrcReg == DstReg && SrcSubIdx == DstSubIdx) {
1817 if (li_->hasInterval(SrcReg)) {
1818 LiveInterval &RegInt = li_->getInterval(SrcReg);
1819 // If def of this move instruction is dead, remove its live range
1820 // from the destination register's live interval.
1821 if (MI->allDefsAreDead()) {
1822 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1823 ShortenDeadCopyLiveRange(RegInt, MI);
1826 li_->RemoveMachineInstrFromMaps(MI);
1827 mii = mbbi->erase(mii);
1834 // Check for now unnecessary kill flags.
1835 if (li_->isNotInMIMap(MI)) continue;
1836 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1837 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1838 MachineOperand &MO = MI->getOperand(i);
1839 if (!MO.isReg() || !MO.isKill()) continue;
1840 unsigned reg = MO.getReg();
1841 if (!reg || !li_->hasInterval(reg)) continue;
1842 if (!li_->getInterval(reg).killedAt(DefIdx))
1843 MO.setIsKill(false);
1852 /// print - Implement the dump method.
1853 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1857 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1858 return new SimpleRegisterCoalescing();
1861 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1862 DEFINING_FILE_FOR(SimpleRegisterCoalescing)