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 "LiveDebugVariables.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/OwningPtr.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
43 STATISTIC(numJoins , "Number of interval joins performed");
44 STATISTIC(numCrossRCs , "Number of cross class joins performed");
45 STATISTIC(numCommutes , "Number of instruction commuting performed");
46 STATISTIC(numExtends , "Number of copies extended");
47 STATISTIC(NumReMats , "Number of instructions re-materialized");
48 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
49 STATISTIC(numAborts , "Number of times interval joining aborted");
50 STATISTIC(numDeadValNo, "Number of valno def marked dead");
52 char SimpleRegisterCoalescing::ID = 0;
54 EnableJoining("join-liveintervals",
55 cl::desc("Coalesce copies (default=true)"),
59 DisableCrossClassJoin("disable-cross-class-join",
60 cl::desc("Avoid coalescing cross register class copies"),
61 cl::init(false), cl::Hidden);
64 DisablePhysicalJoin("disable-physical-join",
65 cl::desc("Avoid coalescing physical register copies"),
66 cl::init(false), cl::Hidden);
68 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
69 "simple-register-coalescing", "Simple Register Coalescing",
71 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
72 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
73 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
74 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
75 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
76 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
77 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
78 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
79 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
80 "simple-register-coalescing", "Simple Register Coalescing",
83 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
85 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequired<AliasAnalysis>();
88 AU.addRequired<LiveIntervals>();
89 AU.addPreserved<LiveIntervals>();
90 AU.addRequired<LiveDebugVariables>();
91 AU.addPreserved<LiveDebugVariables>();
92 AU.addPreserved<SlotIndexes>();
93 AU.addRequired<MachineLoopInfo>();
94 AU.addPreserved<MachineLoopInfo>();
95 AU.addPreservedID(MachineDominatorsID);
97 AU.addPreservedID(StrongPHIEliminationID);
99 AU.addPreservedID(PHIEliminationID);
100 AU.addPreservedID(TwoAddressInstructionPassID);
101 MachineFunctionPass::getAnalysisUsage(AU);
104 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
105 /// being the source and IntB being the dest, thus this defines a value number
106 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
107 /// see if we can merge these two pieces of B into a single value number,
108 /// eliminating a copy. For example:
112 /// B1 = A3 <- this copy
114 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
115 /// value number to be replaced with B0 (which simplifies the B liveinterval).
117 /// This returns true if an interval was modified.
119 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
120 MachineInstr *CopyMI) {
121 // Bail if there is no dst interval - can happen when merging physical subreg
123 if (!li_->hasInterval(CP.getDstReg()))
127 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
129 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
130 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
132 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
133 // the example above.
134 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
135 if (BLR == IntB.end()) return false;
136 VNInfo *BValNo = BLR->valno;
138 // Get the location that B is defined at. Two options: either this value has
139 // an unknown definition point or it is defined at CopyIdx. If unknown, we
141 if (!BValNo->isDefByCopy()) return false;
142 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
144 // AValNo is the value number in A that defines the copy, A3 in the example.
145 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
146 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
147 // The live range might not exist after fun with physreg coalescing.
148 if (ALR == IntA.end()) return false;
149 VNInfo *AValNo = ALR->valno;
150 // If it's re-defined by an early clobber somewhere in the live range, then
151 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
153 // 172 %ECX<def> = MOV32rr %reg1039<kill>
154 // 180 INLINEASM <es:subl $5,$1
155 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
157 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
158 // 188 %EAX<def> = MOV32rr %EAX<kill>
159 // 196 %ECX<def> = MOV32rr %ECX<kill>
160 // 204 %ECX<def> = MOV32rr %ECX<kill>
161 // 212 %EAX<def> = MOV32rr %EAX<kill>
162 // 220 %EAX<def> = MOV32rr %EAX
163 // 228 %reg1039<def> = MOV32rr %ECX<kill>
164 // The early clobber operand ties ECX input to the ECX def.
166 // The live interval of ECX is represented as this:
167 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
168 // The coalescer has no idea there was a def in the middle of [174,230].
169 if (AValNo->hasRedefByEC())
172 // If AValNo is defined as a copy from IntB, we can potentially process this.
173 // Get the instruction that defines this value number.
174 if (!CP.isCoalescable(AValNo->getCopy()))
177 // Get the LiveRange in IntB that this value number starts with.
178 LiveInterval::iterator ValLR =
179 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
180 if (ValLR == IntB.end())
183 // Make sure that the end of the live range is inside the same block as
185 MachineInstr *ValLREndInst =
186 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
187 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
190 // Okay, we now know that ValLR ends in the same block that the CopyMI
191 // live-range starts. If there are no intervening live ranges between them in
192 // IntB, we can merge them.
193 if (ValLR+1 != BLR) return false;
195 // If a live interval is a physical register, conservatively check if any
196 // of its sub-registers is overlapping the live interval of the virtual
197 // register. If so, do not coalesce.
198 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
199 *tri_->getSubRegisters(IntB.reg)) {
200 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
201 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
203 dbgs() << "\t\tInterfere with sub-register ";
204 li_->getInterval(*SR).print(dbgs(), tri_);
211 dbgs() << "Extending: ";
212 IntB.print(dbgs(), tri_);
215 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
216 // We are about to delete CopyMI, so need to remove it as the 'instruction
217 // that defines this value #'. Update the valnum with the new defining
219 BValNo->def = FillerStart;
222 // Okay, we can merge them. We need to insert a new liverange:
223 // [ValLR.end, BLR.begin) of either value number, then we merge the
224 // two value numbers.
225 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
227 // If the IntB live range is assigned to a physical register, and if that
228 // physreg has sub-registers, update their live intervals as well.
229 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
230 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
231 if (!li_->hasInterval(*SR))
233 LiveInterval &SRLI = li_->getInterval(*SR);
234 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
235 SRLI.getNextValue(FillerStart, 0,
236 li_->getVNInfoAllocator())));
240 // Okay, merge "B1" into the same value number as "B0".
241 if (BValNo != ValLR->valno) {
242 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
245 dbgs() << " result = ";
246 IntB.print(dbgs(), tri_);
250 // If the source instruction was killing the source register before the
251 // merge, unset the isKill marker given the live range has been extended.
252 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
254 ValLREndInst->getOperand(UIdx).setIsKill(false);
257 // If the copy instruction was killing the destination register before the
258 // merge, find the last use and trim the live range. That will also add the
260 if (ALR->end == CopyIdx)
261 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
267 /// HasOtherReachingDefs - Return true if there are definitions of IntB
268 /// other than BValNo val# that can reach uses of AValno val# of IntA.
269 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
273 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
275 if (AI->valno != AValNo) continue;
276 LiveInterval::Ranges::iterator BI =
277 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
278 if (BI != IntB.ranges.begin())
280 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
281 if (BI->valno == BValNo)
283 if (BI->start <= AI->start && BI->end > AI->start)
285 if (BI->start > AI->start && BI->start < AI->end)
292 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
293 /// IntA being the source and IntB being the dest, thus this defines a value
294 /// number in IntB. If the source value number (in IntA) is defined by a
295 /// commutable instruction and its other operand is coalesced to the copy dest
296 /// register, see if we can transform the copy into a noop by commuting the
297 /// definition. For example,
299 /// A3 = op A2 B0<kill>
301 /// B1 = A3 <- this copy
303 /// = op A3 <- more uses
307 /// B2 = op B0 A2<kill>
309 /// B1 = B2 <- now an identify copy
311 /// = op B2 <- more uses
313 /// This returns true if an interval was modified.
315 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
316 MachineInstr *CopyMI) {
317 // FIXME: For now, only eliminate the copy by commuting its def when the
318 // source register is a virtual register. We want to guard against cases
319 // where the copy is a back edge copy and commuting the def lengthen the
320 // live interval of the source register to the entire loop.
321 if (CP.isPhys() && CP.isFlipped())
324 // Bail if there is no dst interval.
325 if (!li_->hasInterval(CP.getDstReg()))
328 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
331 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
333 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
335 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
336 // the example above.
337 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
338 if (!BValNo || !BValNo->isDefByCopy())
341 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
343 // AValNo is the value number in A that defines the copy, A3 in the example.
344 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
345 assert(AValNo && "COPY source not live");
347 // If other defs can reach uses of this def, then it's not safe to perform
349 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
351 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
354 const TargetInstrDesc &TID = DefMI->getDesc();
355 if (!TID.isCommutable())
357 // If DefMI is a two-address instruction then commuting it will change the
358 // destination register.
359 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
360 assert(DefIdx != -1);
362 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
364 unsigned Op1, Op2, NewDstIdx;
365 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
369 else if (Op2 == UseOpIdx)
374 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
375 unsigned NewReg = NewDstMO.getReg();
376 if (NewReg != IntB.reg || !NewDstMO.isKill())
379 // Make sure there are no other definitions of IntB that would reach the
380 // uses which the new definition can reach.
381 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
384 // Abort if the aliases of IntB.reg have values that are not simply the
385 // clobbers from the superreg.
386 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
387 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
388 if (li_->hasInterval(*AS) &&
389 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
392 // If some of the uses of IntA.reg is already coalesced away, return false.
393 // It's not possible to determine whether it's safe to perform the coalescing.
394 for (MachineRegisterInfo::use_nodbg_iterator UI =
395 mri_->use_nodbg_begin(IntA.reg),
396 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
397 MachineInstr *UseMI = &*UI;
398 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
399 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
400 if (ULR == IntA.end())
402 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
406 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
409 // At this point we have decided that it is legal to do this
410 // transformation. Start by commuting the instruction.
411 MachineBasicBlock *MBB = DefMI->getParent();
412 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
415 if (NewMI != DefMI) {
416 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
417 MBB->insert(DefMI, NewMI);
420 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
421 NewMI->getOperand(OpIdx).setIsKill();
423 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
432 // Update uses of IntA of the specific Val# with IntB.
433 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
434 UE = mri_->use_end(); UI != UE;) {
435 MachineOperand &UseMO = UI.getOperand();
436 MachineInstr *UseMI = &*UI;
438 if (JoinedCopies.count(UseMI))
440 if (UseMI->isDebugValue()) {
441 // FIXME These don't have an instruction index. Not clear we have enough
442 // info to decide whether to do this replacement or not. For now do it.
443 UseMO.setReg(NewReg);
446 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
447 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
448 if (ULR == IntA.end() || ULR->valno != AValNo)
450 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
451 UseMO.substPhysReg(NewReg, *tri_);
453 UseMO.setReg(NewReg);
456 if (!UseMI->isCopy())
458 if (UseMI->getOperand(0).getReg() != IntB.reg ||
459 UseMI->getOperand(0).getSubReg())
462 // This copy will become a noop. If it's defining a new val#, merge it into
464 SlotIndex DefIdx = UseIdx.getDefIndex();
465 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
468 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
469 assert(DVNI->def == DefIdx);
470 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
471 JoinedCopies.insert(UseMI);
474 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
476 VNInfo *ValNo = BValNo;
477 ValNo->def = AValNo->def;
479 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
481 if (AI->valno != AValNo) continue;
482 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
484 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
486 IntA.removeValNo(AValNo);
487 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
492 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
493 /// fallthoughs to SuccMBB.
494 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
495 MachineBasicBlock *SuccMBB,
496 const TargetInstrInfo *tii_) {
499 MachineBasicBlock *TBB = 0, *FBB = 0;
500 SmallVector<MachineOperand, 4> Cond;
501 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
502 MBB->isSuccessor(SuccMBB);
505 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
506 /// from a physical register live interval as well as from the live intervals
507 /// of its sub-registers.
508 static void removeRange(LiveInterval &li,
509 SlotIndex Start, SlotIndex End,
510 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
511 li.removeRange(Start, End, true);
512 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
513 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
514 if (!li_->hasInterval(*SR))
516 LiveInterval &sli = li_->getInterval(*SR);
517 SlotIndex RemoveStart = Start;
518 SlotIndex RemoveEnd = Start;
520 while (RemoveEnd != End) {
521 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
524 RemoveEnd = (LR->end < End) ? LR->end : End;
525 sli.removeRange(RemoveStart, RemoveEnd, true);
526 RemoveStart = RemoveEnd;
532 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
533 /// as the copy instruction, trim the live interval to the last use and return
536 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
537 MachineBasicBlock *CopyMBB,
539 const LiveRange *LR) {
540 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
541 SlotIndex LastUseIdx;
542 MachineOperand *LastUse =
543 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
545 MachineInstr *LastUseMI = LastUse->getParent();
546 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
553 // r1025<dead> = r1024<kill>
554 if (MBBStart < LR->end)
555 removeRange(li, MBBStart, LR->end, li_, tri_);
559 // There are uses before the copy, just shorten the live range to the end
561 LastUse->setIsKill();
562 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
563 if (LastUseMI->isCopy()) {
564 MachineOperand &DefMO = LastUseMI->getOperand(0);
565 if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
572 if (LR->start <= MBBStart && LR->end > MBBStart) {
573 if (LR->start == li_->getZeroIndex()) {
574 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
575 // Live-in to the function but dead. Remove it from entry live-in set.
576 mf_->begin()->removeLiveIn(li.reg);
578 // FIXME: Shorten intervals in BBs that reaches this BB.
584 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
585 /// computation, replace the copy by rematerialize the definition.
586 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
589 MachineInstr *CopyMI) {
590 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
591 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
592 assert(SrcLR != SrcInt.end() && "Live range not found!");
593 VNInfo *ValNo = SrcLR->valno;
594 // If other defs can reach uses of this def, then it's not safe to perform
596 if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
598 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
601 assert(DefMI && "Defining instruction disappeared");
602 const TargetInstrDesc &TID = DefMI->getDesc();
603 if (!TID.isAsCheapAsAMove())
605 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
607 bool SawStore = false;
608 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
610 if (TID.getNumDefs() != 1)
612 if (!DefMI->isImplicitDef()) {
613 // Make sure the copy destination register class fits the instruction
614 // definition register class. The mismatch can happen as a result of earlier
615 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
616 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
617 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
618 if (mri_->getRegClass(DstReg) != RC)
620 } else if (!RC->contains(DstReg))
624 // If destination register has a sub-register index on it, make sure it mtches
625 // the instruction register class.
627 const TargetInstrDesc &TID = DefMI->getDesc();
628 if (TID.getNumDefs() != 1)
630 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
631 const TargetRegisterClass *DstSubRC =
632 DstRC->getSubRegisterRegClass(DstSubIdx);
633 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
636 else if (DefRC != DstSubRC)
640 RemoveCopyFlag(DstReg, CopyMI);
642 // If copy kills the source register, find the last use and propagate
644 bool checkForDeadDef = false;
645 MachineBasicBlock *MBB = CopyMI->getParent();
646 if (SrcLR->end == CopyIdx.getDefIndex())
647 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
648 checkForDeadDef = true;
651 MachineBasicBlock::iterator MII =
652 llvm::next(MachineBasicBlock::iterator(CopyMI));
653 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
654 MachineInstr *NewMI = prior(MII);
656 if (checkForDeadDef) {
657 // PR4090 fix: Trim interval failed because there was no use of the
658 // source interval in this MBB. If the def is in this MBB too then we
659 // should mark it dead:
660 if (DefMI->getParent() == MBB) {
661 DefMI->addRegisterDead(SrcInt.reg, tri_);
662 SrcLR->end = SrcLR->start.getNextSlot();
666 // CopyMI may have implicit operands, transfer them over to the newly
667 // rematerialized instruction. And update implicit def interval valnos.
668 for (unsigned i = CopyMI->getDesc().getNumOperands(),
669 e = CopyMI->getNumOperands(); i != e; ++i) {
670 MachineOperand &MO = CopyMI->getOperand(i);
671 if (MO.isReg() && MO.isImplicit())
672 NewMI->addOperand(MO);
674 RemoveCopyFlag(MO.getReg(), CopyMI);
677 NewMI->copyImplicitOps(CopyMI);
678 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
679 CopyMI->eraseFromParent();
680 ReMatCopies.insert(CopyMI);
681 ReMatDefs.insert(DefMI);
682 DEBUG(dbgs() << "Remat: " << *NewMI);
687 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
688 /// update the subregister number if it is not zero. If DstReg is a
689 /// physical register and the existing subregister number of the def / use
690 /// being updated is not zero, make sure to set it to the correct physical
693 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
694 bool DstIsPhys = CP.isPhys();
695 unsigned SrcReg = CP.getSrcReg();
696 unsigned DstReg = CP.getDstReg();
697 unsigned SubIdx = CP.getSubIdx();
699 // Update LiveDebugVariables.
700 ldv_->renameRegister(SrcReg, DstReg, SubIdx);
702 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
703 MachineInstr *UseMI = I.skipInstruction();) {
704 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
707 if (UseMI->isCopy() &&
708 !UseMI->getOperand(1).getSubReg() &&
709 !UseMI->getOperand(0).getSubReg() &&
710 UseMI->getOperand(1).getReg() == SrcReg &&
711 UseMI->getOperand(0).getReg() != SrcReg &&
712 UseMI->getOperand(0).getReg() != DstReg &&
713 !JoinedCopies.count(UseMI) &&
714 ReMaterializeTrivialDef(li_->getInterval(SrcReg),
715 UseMI->getOperand(0).getReg(), 0, UseMI))
719 SmallVector<unsigned,8> Ops;
721 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
722 bool Kills = false, Deads = false;
724 // Replace SrcReg with DstReg in all UseMI operands.
725 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
726 MachineOperand &MO = UseMI->getOperand(Ops[i]);
727 Kills |= MO.isKill();
728 Deads |= MO.isDead();
731 MO.substPhysReg(DstReg, *tri_);
733 MO.substVirtReg(DstReg, SubIdx, *tri_);
736 // This instruction is a copy that will be removed.
737 if (JoinedCopies.count(UseMI))
741 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
742 // read-modify-write of DstReg.
744 UseMI->addRegisterDead(DstReg, tri_);
745 else if (!Reads && Writes)
746 UseMI->addRegisterDefined(DstReg, tri_);
748 // Kill flags apply to the whole physical register.
749 if (DstIsPhys && Kills)
750 UseMI->addRegisterKilled(DstReg, tri_);
754 dbgs() << "\t\tupdated: ";
755 if (!UseMI->isDebugValue())
756 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
762 /// removeIntervalIfEmpty - Check if the live interval of a physical register
763 /// is empty, if so remove it and also remove the empty intervals of its
764 /// sub-registers. Return true if live interval is removed.
765 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
766 const TargetRegisterInfo *tri_) {
768 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
769 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
770 if (!li_->hasInterval(*SR))
772 LiveInterval &sli = li_->getInterval(*SR);
774 li_->removeInterval(*SR);
776 li_->removeInterval(li.reg);
782 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
783 /// Return true if live interval is removed.
784 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
785 MachineInstr *CopyMI) {
786 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
787 LiveInterval::iterator MLR =
788 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
790 return false; // Already removed by ShortenDeadCopySrcLiveRange.
791 SlotIndex RemoveStart = MLR->start;
792 SlotIndex RemoveEnd = MLR->end;
793 SlotIndex DefIdx = CopyIdx.getDefIndex();
794 // Remove the liverange that's defined by this.
795 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
796 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
797 return removeIntervalIfEmpty(li, li_, tri_);
802 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
803 /// the val# it defines. If the live interval becomes empty, remove it as well.
804 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
805 MachineInstr *DefMI) {
806 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
807 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
808 if (DefIdx != MLR->valno->def)
810 li.removeValNo(MLR->valno);
811 return removeIntervalIfEmpty(li, li_, tri_);
814 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
815 const MachineInstr *CopyMI) {
816 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
817 if (li_->hasInterval(DstReg)) {
818 LiveInterval &LI = li_->getInterval(DstReg);
819 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
820 if (LR->valno->def == DefIdx)
821 LR->valno->setCopy(0);
823 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
825 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
826 if (!li_->hasInterval(*AS))
828 LiveInterval &LI = li_->getInterval(*AS);
829 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
830 if (LR->valno->def == DefIdx)
831 LR->valno->setCopy(0);
835 /// PropagateDeadness - Propagate the dead marker to the instruction which
836 /// defines the val#.
837 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
838 SlotIndex &LRStart, LiveIntervals *li_,
839 const TargetRegisterInfo* tri_) {
840 MachineInstr *DefMI =
841 li_->getInstructionFromIndex(LRStart.getDefIndex());
842 if (DefMI && DefMI != CopyMI) {
843 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
845 DefMI->getOperand(DeadIdx).setIsDead();
847 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
848 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
849 LRStart = LRStart.getNextSlot();
853 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
854 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
855 /// ends the live range there. If there isn't another use, then this live range
856 /// is dead. Return true if live interval is removed.
858 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
859 MachineInstr *CopyMI) {
860 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
861 if (CopyIdx == SlotIndex()) {
862 // FIXME: special case: function live in. It can be a general case if the
863 // first instruction index starts at > 0 value.
864 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
865 // Live-in to the function but dead. Remove it from entry live-in set.
866 if (mf_->begin()->isLiveIn(li.reg))
867 mf_->begin()->removeLiveIn(li.reg);
868 if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
869 removeRange(li, LR->start, LR->end, li_, tri_);
870 return removeIntervalIfEmpty(li, li_, tri_);
873 LiveInterval::iterator LR =
874 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
876 // Livein but defined by a phi.
879 SlotIndex RemoveStart = LR->start;
880 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
881 if (LR->end > RemoveEnd)
882 // More uses past this copy? Nothing to do.
885 // If there is a last use in the same bb, we can't remove the live range.
886 // Shorten the live interval and return.
887 MachineBasicBlock *CopyMBB = CopyMI->getParent();
888 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
891 // There are other kills of the val#. Nothing to do.
892 if (!li.isOnlyLROfValNo(LR))
895 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
896 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
897 // If the live range starts in another mbb and the copy mbb is not a fall
898 // through mbb, then we can only cut the range from the beginning of the
900 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
902 if (LR->valno->def == RemoveStart) {
903 // If the def MI defines the val# and this copy is the only kill of the
904 // val#, then propagate the dead marker.
905 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
909 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
910 return removeIntervalIfEmpty(li, li_, tri_);
914 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
915 /// two virtual registers from different register classes.
917 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
919 const TargetRegisterClass *SrcRC,
920 const TargetRegisterClass *DstRC,
921 const TargetRegisterClass *NewRC) {
922 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
923 // This heuristics is good enough in practice, but it's obviously not *right*.
924 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
925 // out all but the most restrictive register classes.
926 if (NewRCCount > 4 ||
927 // Early exit if the function is fairly small, coalesce aggressively if
928 // that's the case. For really special register classes with 3 or
929 // fewer registers, be a bit more careful.
930 (li_->getFuncInstructionCount() / NewRCCount) < 8)
932 LiveInterval &SrcInt = li_->getInterval(SrcReg);
933 LiveInterval &DstInt = li_->getInterval(DstReg);
934 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
935 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
936 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
938 // Estimate *register use density*. If it doubles or more, abort.
939 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
940 mri_->use_nodbg_end());
941 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
942 mri_->use_nodbg_end());
943 unsigned NewUses = SrcUses + DstUses;
944 unsigned NewSize = SrcSize + DstSize;
945 if (SrcRC != NewRC && SrcSize > NewRCCount) {
946 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
947 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
950 if (DstRC != NewRC && DstSize > NewRCCount) {
951 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
952 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
959 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
960 /// which are the src/dst of the copy instruction CopyMI. This returns true
961 /// if the copy was successfully coalesced away. If it is not currently
962 /// possible to coalesce this interval, but it may be possible if other
963 /// things get coalesced, then it returns true by reference in 'Again'.
964 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
965 MachineInstr *CopyMI = TheCopy.MI;
968 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
969 return false; // Already done.
971 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
973 CoalescerPair CP(*tii_, *tri_);
974 if (!CP.setRegisters(CopyMI)) {
975 DEBUG(dbgs() << "\tNot coalescable.\n");
979 // If they are already joined we continue.
980 if (CP.getSrcReg() == CP.getDstReg()) {
981 DEBUG(dbgs() << "\tCopy already coalesced.\n");
982 return false; // Not coalescable.
985 if (DisablePhysicalJoin && CP.isPhys()) {
986 DEBUG(dbgs() << "\tPhysical joins disabled.\n");
990 DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
994 DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
995 // Only coalesce to allocatable physreg.
996 if (!li_->isAllocatable(CP.getDstReg())) {
997 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
998 return false; // Not coalescable.
1002 dbgs() << " with reg%" << CP.getDstReg();
1004 dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1005 dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1008 // Avoid constraining virtual register regclass too much.
1009 if (CP.isCrossClass()) {
1010 if (DisableCrossClassJoin) {
1011 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1014 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1015 mri_->getRegClass(CP.getSrcReg()),
1016 mri_->getRegClass(CP.getDstReg()),
1018 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1019 << CP.getNewRC()->getName() << ".\n");
1020 Again = true; // May be possible to coalesce later.
1025 // When possible, let DstReg be the larger interval.
1026 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1027 li_->getInterval(CP.getDstReg()).ranges.size())
1031 // We need to be careful about coalescing a source physical register with a
1032 // virtual register. Once the coalescing is done, it cannot be broken and
1033 // these are not spillable! If the destination interval uses are far away,
1034 // think twice about coalescing them!
1035 // FIXME: Why are we skipping this test for partial copies?
1036 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1037 if (!CP.isPartial() && CP.isPhys()) {
1038 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1040 // Don't join with physregs that have a ridiculous number of live
1041 // ranges. The data structure performance is really bad when that
1043 if (li_->hasInterval(CP.getDstReg()) &&
1044 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1047 << "\tPhysical register live interval too complicated, abort!\n");
1051 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1052 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1053 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1054 if (Length > Threshold &&
1055 std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1056 mri_->use_nodbg_end()) * Threshold < Length) {
1057 // Before giving up coalescing, if definition of source is defined by
1058 // trivial computation, try rematerializing it.
1059 if (!CP.isFlipped() &&
1060 ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1064 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1065 Again = true; // May be possible to coalesce later.
1070 // Okay, attempt to join these two intervals. On failure, this returns false.
1071 // Otherwise, if one of the intervals being joined is a physreg, this method
1072 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1073 // been modified, so we can use this information below to update aliases.
1074 if (!JoinIntervals(CP)) {
1075 // Coalescing failed.
1077 // If definition of source is defined by trivial computation, try
1078 // rematerializing it.
1079 if (!CP.isFlipped() &&
1080 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1081 CP.getDstReg(), 0, CopyMI))
1084 // If we can eliminate the copy without merging the live ranges, do so now.
1085 if (!CP.isPartial()) {
1086 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1087 RemoveCopyByCommutingDef(CP, CopyMI)) {
1088 JoinedCopies.insert(CopyMI);
1089 DEBUG(dbgs() << "\tTrivial!\n");
1094 // Otherwise, we are unable to join the intervals.
1095 DEBUG(dbgs() << "\tInterference!\n");
1096 Again = true; // May be possible to coalesce later.
1100 // Coalescing to a virtual register that is of a sub-register class of the
1101 // other. Make sure the resulting register is set to the right register class.
1102 if (CP.isCrossClass()) {
1104 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1107 // Remember to delete the copy instruction.
1108 JoinedCopies.insert(CopyMI);
1110 UpdateRegDefsUses(CP);
1112 // If we have extended the live range of a physical register, make sure we
1113 // update live-in lists as well.
1115 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1116 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1117 // ranges for this, and they are preserved.
1118 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1119 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1121 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1122 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1123 MachineBasicBlock &block = *BlockSeq[idx];
1124 if (!block.isLiveIn(CP.getDstReg()))
1125 block.addLiveIn(CP.getDstReg());
1131 // SrcReg is guarateed to be the register whose live interval that is
1133 li_->removeInterval(CP.getSrcReg());
1135 // Update regalloc hint.
1136 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1139 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1140 dbgs() << "\tJoined. Result = ";
1141 DstInt.print(dbgs(), tri_);
1149 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1150 /// compute what the resultant value numbers for each value in the input two
1151 /// ranges will be. This is complicated by copies between the two which can
1152 /// and will commonly cause multiple value numbers to be merged into one.
1154 /// VN is the value number that we're trying to resolve. InstDefiningValue
1155 /// keeps track of the new InstDefiningValue assignment for the result
1156 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1157 /// whether a value in this or other is a copy from the opposite set.
1158 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1159 /// already been assigned.
1161 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1162 /// contains the value number the copy is from.
1164 static unsigned ComputeUltimateVN(VNInfo *VNI,
1165 SmallVector<VNInfo*, 16> &NewVNInfo,
1166 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1167 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1168 SmallVector<int, 16> &ThisValNoAssignments,
1169 SmallVector<int, 16> &OtherValNoAssignments) {
1170 unsigned VN = VNI->id;
1172 // If the VN has already been computed, just return it.
1173 if (ThisValNoAssignments[VN] >= 0)
1174 return ThisValNoAssignments[VN];
1175 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1177 // If this val is not a copy from the other val, then it must be a new value
1178 // number in the destination.
1179 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1180 if (I == ThisFromOther.end()) {
1181 NewVNInfo.push_back(VNI);
1182 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1184 VNInfo *OtherValNo = I->second;
1186 // Otherwise, this *is* a copy from the RHS. If the other side has already
1187 // been computed, return it.
1188 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1189 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1191 // Mark this value number as currently being computed, then ask what the
1192 // ultimate value # of the other value is.
1193 ThisValNoAssignments[VN] = -2;
1194 unsigned UltimateVN =
1195 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1196 OtherValNoAssignments, ThisValNoAssignments);
1197 return ThisValNoAssignments[VN] = UltimateVN;
1200 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1202 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1203 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1204 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1206 // If a live interval is a physical register, check for interference with any
1207 // aliases. The interference check implemented here is a bit more conservative
1208 // than the full interfeence check below. We allow overlapping live ranges
1209 // only when one is a copy of the other.
1211 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1212 if (!li_->hasInterval(*AS))
1214 const LiveInterval &LHS = li_->getInterval(*AS);
1215 LiveInterval::const_iterator LI = LHS.begin();
1216 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1218 LI = std::lower_bound(LI, LHS.end(), RI->start);
1219 // Does LHS have an overlapping live range starting before RI?
1220 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1221 (RI->start != RI->valno->def ||
1222 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1224 dbgs() << "\t\tInterference from alias: ";
1225 LHS.print(dbgs(), tri_);
1226 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1231 // Check that LHS ranges beginning in this range are copies.
1232 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1233 if (LI->start != LI->valno->def ||
1234 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1236 dbgs() << "\t\tInterference from alias: ";
1237 LHS.print(dbgs(), tri_);
1238 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1247 // Compute the final value assignment, assuming that the live ranges can be
1249 SmallVector<int, 16> LHSValNoAssignments;
1250 SmallVector<int, 16> RHSValNoAssignments;
1251 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1252 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1253 SmallVector<VNInfo*, 16> NewVNInfo;
1255 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1256 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1258 // Loop over the value numbers of the LHS, seeing if any are defined from
1260 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1263 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1266 // Never join with a register that has EarlyClobber redefs.
1267 if (VNI->hasRedefByEC())
1270 // DstReg is known to be a register in the LHS interval. If the src is
1271 // from the RHS interval, we can use its value #.
1272 if (!CP.isCoalescable(VNI->getCopy()))
1275 // Figure out the value # from the RHS.
1276 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1277 // The copy could be to an aliased physreg.
1279 LHSValsDefinedFromRHS[VNI] = lr->valno;
1282 // Loop over the value numbers of the RHS, seeing if any are defined from
1284 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1287 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1290 // Never join with a register that has EarlyClobber redefs.
1291 if (VNI->hasRedefByEC())
1294 // DstReg is known to be a register in the RHS interval. If the src is
1295 // from the LHS interval, we can use its value #.
1296 if (!CP.isCoalescable(VNI->getCopy()))
1299 // Figure out the value # from the LHS.
1300 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1301 // The copy could be to an aliased physreg.
1303 RHSValsDefinedFromLHS[VNI] = lr->valno;
1306 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1307 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1308 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1310 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1313 unsigned VN = VNI->id;
1314 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1316 ComputeUltimateVN(VNI, NewVNInfo,
1317 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1318 LHSValNoAssignments, RHSValNoAssignments);
1320 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1323 unsigned VN = VNI->id;
1324 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1326 // If this value number isn't a copy from the LHS, it's a new number.
1327 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1328 NewVNInfo.push_back(VNI);
1329 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1333 ComputeUltimateVN(VNI, NewVNInfo,
1334 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1335 RHSValNoAssignments, LHSValNoAssignments);
1338 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1339 // interval lists to see if these intervals are coalescable.
1340 LiveInterval::const_iterator I = LHS.begin();
1341 LiveInterval::const_iterator IE = LHS.end();
1342 LiveInterval::const_iterator J = RHS.begin();
1343 LiveInterval::const_iterator JE = RHS.end();
1345 // Skip ahead until the first place of potential sharing.
1346 if (I != IE && J != JE) {
1347 if (I->start < J->start) {
1348 I = std::upper_bound(I, IE, J->start);
1349 if (I != LHS.begin()) --I;
1350 } else if (J->start < I->start) {
1351 J = std::upper_bound(J, JE, I->start);
1352 if (J != RHS.begin()) --J;
1356 while (I != IE && J != JE) {
1357 // Determine if these two live ranges overlap.
1359 if (I->start < J->start) {
1360 Overlaps = I->end > J->start;
1362 Overlaps = J->end > I->start;
1365 // If so, check value # info to determine if they are really different.
1367 // If the live range overlap will map to the same value number in the
1368 // result liverange, we can still coalesce them. If not, we can't.
1369 if (LHSValNoAssignments[I->valno->id] !=
1370 RHSValNoAssignments[J->valno->id])
1372 // If it's re-defined by an early clobber somewhere in the live range,
1373 // then conservatively abort coalescing.
1374 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1378 if (I->end < J->end)
1384 // Update kill info. Some live ranges are extended due to copy coalescing.
1385 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1386 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1387 VNInfo *VNI = I->first;
1388 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1389 if (VNI->hasPHIKill())
1390 NewVNInfo[LHSValID]->setHasPHIKill(true);
1393 // Update kill info. Some live ranges are extended due to copy coalescing.
1394 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1395 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1396 VNInfo *VNI = I->first;
1397 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1398 if (VNI->hasPHIKill())
1399 NewVNInfo[RHSValID]->setHasPHIKill(true);
1402 if (LHSValNoAssignments.empty())
1403 LHSValNoAssignments.push_back(-1);
1404 if (RHSValNoAssignments.empty())
1405 RHSValNoAssignments.push_back(-1);
1407 // If we get here, we know that we can coalesce the live ranges. Ask the
1408 // intervals to coalesce themselves now.
1409 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1415 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1416 // depth of the basic block (the unsigned), and then on the MBB number.
1417 struct DepthMBBCompare {
1418 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1419 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1420 // Deeper loops first
1421 if (LHS.first != RHS.first)
1422 return LHS.first > RHS.first;
1424 // Prefer blocks that are more connected in the CFG. This takes care of
1425 // the most difficult copies first while intervals are short.
1426 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1427 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1431 // As a last resort, sort by block number.
1432 return LHS.second->getNumber() < RHS.second->getNumber();
1437 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1438 std::vector<CopyRec> &TryAgain) {
1439 DEBUG(dbgs() << MBB->getName() << ":\n");
1441 std::vector<CopyRec> VirtCopies;
1442 std::vector<CopyRec> PhysCopies;
1443 std::vector<CopyRec> ImpDefCopies;
1444 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1446 MachineInstr *Inst = MII++;
1448 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1449 unsigned SrcReg, DstReg;
1450 if (Inst->isCopy()) {
1451 DstReg = Inst->getOperand(0).getReg();
1452 SrcReg = Inst->getOperand(1).getReg();
1453 } else if (Inst->isSubregToReg()) {
1454 DstReg = Inst->getOperand(0).getReg();
1455 SrcReg = Inst->getOperand(2).getReg();
1459 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1460 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1461 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1462 ImpDefCopies.push_back(CopyRec(Inst, 0));
1463 else if (SrcIsPhys || DstIsPhys)
1464 PhysCopies.push_back(CopyRec(Inst, 0));
1466 VirtCopies.push_back(CopyRec(Inst, 0));
1469 // Try coalescing implicit copies and insert_subreg <undef> first,
1470 // followed by copies to / from physical registers, then finally copies
1471 // from virtual registers to virtual registers.
1472 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1473 CopyRec &TheCopy = ImpDefCopies[i];
1475 if (!JoinCopy(TheCopy, Again))
1477 TryAgain.push_back(TheCopy);
1479 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1480 CopyRec &TheCopy = PhysCopies[i];
1482 if (!JoinCopy(TheCopy, Again))
1484 TryAgain.push_back(TheCopy);
1486 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1487 CopyRec &TheCopy = VirtCopies[i];
1489 if (!JoinCopy(TheCopy, Again))
1491 TryAgain.push_back(TheCopy);
1495 void SimpleRegisterCoalescing::joinIntervals() {
1496 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1498 std::vector<CopyRec> TryAgainList;
1499 if (loopInfo->empty()) {
1500 // If there are no loops in the function, join intervals in function order.
1501 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1503 CopyCoalesceInMBB(I, TryAgainList);
1505 // Otherwise, join intervals in inner loops before other intervals.
1506 // Unfortunately we can't just iterate over loop hierarchy here because
1507 // there may be more MBB's than BB's. Collect MBB's for sorting.
1509 // Join intervals in the function prolog first. We want to join physical
1510 // registers with virtual registers before the intervals got too long.
1511 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1512 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1513 MachineBasicBlock *MBB = I;
1514 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1517 // Sort by loop depth.
1518 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1520 // Finally, join intervals in loop nest order.
1521 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1522 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1525 // Joining intervals can allow other intervals to be joined. Iteratively join
1526 // until we make no progress.
1527 bool ProgressMade = true;
1528 while (ProgressMade) {
1529 ProgressMade = false;
1531 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1532 CopyRec &TheCopy = TryAgainList[i];
1537 bool Success = JoinCopy(TheCopy, Again);
1538 if (Success || !Again) {
1539 TheCopy.MI = 0; // Mark this one as done.
1540 ProgressMade = true;
1546 /// Return true if the two specified registers belong to different register
1547 /// classes. The registers may be either phys or virt regs.
1549 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1550 unsigned RegB) const {
1551 // Get the register classes for the first reg.
1552 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1553 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1554 "Shouldn't consider two physregs!");
1555 return !mri_->getRegClass(RegB)->contains(RegA);
1558 // Compare against the regclass for the second reg.
1559 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1560 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1561 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1562 return RegClassA != RegClassB;
1564 return !RegClassA->contains(RegB);
1567 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1568 /// between cycles Start and End or NULL if there are no uses.
1570 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1573 SlotIndex &UseIdx) const{
1574 UseIdx = SlotIndex();
1575 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1576 MachineOperand *LastUse = NULL;
1577 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1578 E = mri_->use_nodbg_end(); I != E; ++I) {
1579 MachineOperand &Use = I.getOperand();
1580 MachineInstr *UseMI = Use.getParent();
1581 if (UseMI->isIdentityCopy())
1583 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1584 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1585 // that compares higher than any other interval.
1586 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1588 UseIdx = Idx.getUseIndex();
1594 SlotIndex s = Start;
1595 SlotIndex e = End.getPrevSlot().getBaseIndex();
1597 // Skip deleted instructions
1598 MachineInstr *MI = li_->getInstructionFromIndex(e);
1599 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1600 e = e.getPrevIndex();
1601 MI = li_->getInstructionFromIndex(e);
1603 if (e < s || MI == NULL)
1606 // Ignore identity copies.
1607 if (!MI->isIdentityCopy())
1608 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1609 MachineOperand &Use = MI->getOperand(i);
1610 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1611 tri_->regsOverlap(Use.getReg(), Reg)) {
1612 UseIdx = e.getUseIndex();
1617 e = e.getPrevIndex();
1623 void SimpleRegisterCoalescing::releaseMemory() {
1624 JoinedCopies.clear();
1625 ReMatCopies.clear();
1629 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1631 mri_ = &fn.getRegInfo();
1632 tm_ = &fn.getTarget();
1633 tri_ = tm_->getRegisterInfo();
1634 tii_ = tm_->getInstrInfo();
1635 li_ = &getAnalysis<LiveIntervals>();
1636 ldv_ = &getAnalysis<LiveDebugVariables>();
1637 AA = &getAnalysis<AliasAnalysis>();
1638 loopInfo = &getAnalysis<MachineLoopInfo>();
1640 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1641 << "********** Function: "
1642 << ((Value*)mf_->getFunction())->getName() << '\n');
1644 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1645 E = tri_->regclass_end(); I != E; ++I)
1646 allocatableRCRegs_.insert(std::make_pair(*I,
1647 tri_->getAllocatableSet(fn, *I)));
1649 // Join (coalesce) intervals if requested.
1650 if (EnableJoining) {
1653 dbgs() << "********** INTERVALS POST JOINING **********\n";
1654 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1656 I->second->print(dbgs(), tri_);
1662 // Perform a final pass over the instructions and compute spill weights
1663 // and remove identity moves.
1664 SmallVector<unsigned, 4> DeadDefs;
1665 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1666 mbbi != mbbe; ++mbbi) {
1667 MachineBasicBlock* mbb = mbbi;
1668 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1670 MachineInstr *MI = mii;
1671 if (JoinedCopies.count(MI)) {
1672 // Delete all coalesced copies.
1673 bool DoDelete = true;
1674 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1675 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1676 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1677 MI->getNumOperands() > 2)
1678 // Do not delete extract_subreg, insert_subreg of physical
1679 // registers unless the definition is dead. e.g.
1680 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1681 // or else the scavenger may complain. LowerSubregs will
1682 // delete them later.
1685 if (MI->allDefsAreDead()) {
1686 LiveInterval &li = li_->getInterval(SrcReg);
1687 if (!ShortenDeadCopySrcLiveRange(li, MI))
1688 ShortenDeadCopyLiveRange(li, MI);
1692 // We need the instruction to adjust liveness, so make it a KILL.
1693 if (MI->isSubregToReg()) {
1694 MI->RemoveOperand(3);
1695 MI->RemoveOperand(1);
1697 MI->setDesc(tii_->get(TargetOpcode::KILL));
1698 mii = llvm::next(mii);
1700 li_->RemoveMachineInstrFromMaps(MI);
1701 mii = mbbi->erase(mii);
1707 // Now check if this is a remat'ed def instruction which is now dead.
1708 if (ReMatDefs.count(MI)) {
1710 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1711 const MachineOperand &MO = MI->getOperand(i);
1714 unsigned Reg = MO.getReg();
1717 if (TargetRegisterInfo::isVirtualRegister(Reg))
1718 DeadDefs.push_back(Reg);
1721 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1722 !mri_->use_nodbg_empty(Reg)) {
1728 while (!DeadDefs.empty()) {
1729 unsigned DeadDef = DeadDefs.back();
1730 DeadDefs.pop_back();
1731 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1733 li_->RemoveMachineInstrFromMaps(mii);
1734 mii = mbbi->erase(mii);
1740 // If the move will be an identity move delete it
1741 if (MI->isIdentityCopy()) {
1742 unsigned SrcReg = MI->getOperand(1).getReg();
1743 if (li_->hasInterval(SrcReg)) {
1744 LiveInterval &RegInt = li_->getInterval(SrcReg);
1745 // If def of this move instruction is dead, remove its live range
1746 // from the destination register's live interval.
1747 if (MI->allDefsAreDead()) {
1748 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1749 ShortenDeadCopyLiveRange(RegInt, MI);
1752 li_->RemoveMachineInstrFromMaps(MI);
1753 mii = mbbi->erase(mii);
1760 // Check for now unnecessary kill flags.
1761 if (li_->isNotInMIMap(MI)) continue;
1762 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1763 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1764 MachineOperand &MO = MI->getOperand(i);
1765 if (!MO.isReg() || !MO.isKill()) continue;
1766 unsigned reg = MO.getReg();
1767 if (!reg || !li_->hasInterval(reg)) continue;
1768 if (!li_->getInterval(reg).killedAt(DefIdx)) {
1769 MO.setIsKill(false);
1772 // When leaving a kill flag on a physreg, check if any subregs should
1774 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1776 for (const unsigned *SR = tri_->getSubRegisters(reg);
1777 unsigned S = *SR; ++SR)
1778 if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1779 MI->addRegisterDefined(S, tri_);
1785 DEBUG(ldv_->dump());
1789 /// print - Implement the dump method.
1790 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1794 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1795 return new SimpleRegisterCoalescing();
1798 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1799 DEFINING_FILE_FOR(SimpleRegisterCoalescing)