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);
63 DisablePhysicalJoin("disable-physical-join",
64 cl::desc("Avoid coalescing physical register copies"),
65 cl::init(false), cl::Hidden);
67 INITIALIZE_AG_PASS(SimpleRegisterCoalescing, RegisterCoalescer,
68 "simple-register-coalescing", "Simple Register Coalescing",
71 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
73 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<AliasAnalysis>();
76 AU.addRequired<LiveIntervals>();
77 AU.addPreserved<LiveIntervals>();
78 AU.addPreserved<SlotIndexes>();
79 AU.addRequired<MachineLoopInfo>();
80 AU.addPreserved<MachineLoopInfo>();
81 AU.addPreservedID(MachineDominatorsID);
83 AU.addPreservedID(StrongPHIEliminationID);
85 AU.addPreservedID(PHIEliminationID);
86 AU.addPreservedID(TwoAddressInstructionPassID);
87 MachineFunctionPass::getAnalysisUsage(AU);
90 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
91 /// being the source and IntB being the dest, thus this defines a value number
92 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
93 /// see if we can merge these two pieces of B into a single value number,
94 /// eliminating a copy. For example:
98 /// B1 = A3 <- this copy
100 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
101 /// value number to be replaced with B0 (which simplifies the B liveinterval).
103 /// This returns true if an interval was modified.
105 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
106 MachineInstr *CopyMI) {
107 // Bail if there is no dst interval - can happen when merging physical subreg
109 if (!li_->hasInterval(CP.getDstReg()))
113 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
115 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
116 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
118 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
119 // the example above.
120 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
121 if (BLR == IntB.end()) return false;
122 VNInfo *BValNo = BLR->valno;
124 // Get the location that B is defined at. Two options: either this value has
125 // an unknown definition point or it is defined at CopyIdx. If unknown, we
127 if (!BValNo->getCopy()) return false;
128 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
130 // AValNo is the value number in A that defines the copy, A3 in the example.
131 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
132 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
133 // The live range might not exist after fun with physreg coalescing.
134 if (ALR == IntA.end()) return false;
135 VNInfo *AValNo = ALR->valno;
136 // If it's re-defined by an early clobber somewhere in the live range, then
137 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
139 // 172 %ECX<def> = MOV32rr %reg1039<kill>
140 // 180 INLINEASM <es:subl $5,$1
141 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
143 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
144 // 188 %EAX<def> = MOV32rr %EAX<kill>
145 // 196 %ECX<def> = MOV32rr %ECX<kill>
146 // 204 %ECX<def> = MOV32rr %ECX<kill>
147 // 212 %EAX<def> = MOV32rr %EAX<kill>
148 // 220 %EAX<def> = MOV32rr %EAX
149 // 228 %reg1039<def> = MOV32rr %ECX<kill>
150 // The early clobber operand ties ECX input to the ECX def.
152 // The live interval of ECX is represented as this:
153 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
154 // The coalescer has no idea there was a def in the middle of [174,230].
155 if (AValNo->hasRedefByEC())
158 // If AValNo is defined as a copy from IntB, we can potentially process this.
159 // Get the instruction that defines this value number.
160 if (!CP.isCoalescable(AValNo->getCopy()))
163 // Get the LiveRange in IntB that this value number starts with.
164 LiveInterval::iterator ValLR =
165 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
166 if (ValLR == IntB.end())
169 // Make sure that the end of the live range is inside the same block as
171 MachineInstr *ValLREndInst =
172 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
173 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
176 // Okay, we now know that ValLR ends in the same block that the CopyMI
177 // live-range starts. If there are no intervening live ranges between them in
178 // IntB, we can merge them.
179 if (ValLR+1 != BLR) return false;
181 // If a live interval is a physical register, conservatively check if any
182 // of its sub-registers is overlapping the live interval of the virtual
183 // register. If so, do not coalesce.
184 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
185 *tri_->getSubRegisters(IntB.reg)) {
186 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
187 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
189 dbgs() << "\t\tInterfere with sub-register ";
190 li_->getInterval(*SR).print(dbgs(), tri_);
197 dbgs() << "Extending: ";
198 IntB.print(dbgs(), tri_);
201 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
202 // We are about to delete CopyMI, so need to remove it as the 'instruction
203 // that defines this value #'. Update the valnum with the new defining
205 BValNo->def = FillerStart;
208 // Okay, we can merge them. We need to insert a new liverange:
209 // [ValLR.end, BLR.begin) of either value number, then we merge the
210 // two value numbers.
211 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
213 // If the IntB live range is assigned to a physical register, and if that
214 // physreg has sub-registers, update their live intervals as well.
215 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
216 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
217 if (!li_->hasInterval(*SR))
219 LiveInterval &SRLI = li_->getInterval(*SR);
220 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
221 SRLI.getNextValue(FillerStart, 0, true,
222 li_->getVNInfoAllocator())));
226 // Okay, merge "B1" into the same value number as "B0".
227 if (BValNo != ValLR->valno) {
228 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
231 dbgs() << " result = ";
232 IntB.print(dbgs(), tri_);
236 // If the source instruction was killing the source register before the
237 // merge, unset the isKill marker given the live range has been extended.
238 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
240 ValLREndInst->getOperand(UIdx).setIsKill(false);
243 // If the copy instruction was killing the destination register before the
244 // merge, find the last use and trim the live range. That will also add the
246 if (ALR->end == CopyIdx)
247 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
253 /// HasOtherReachingDefs - Return true if there are definitions of IntB
254 /// other than BValNo val# that can reach uses of AValno val# of IntA.
255 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
259 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
261 if (AI->valno != AValNo) continue;
262 LiveInterval::Ranges::iterator BI =
263 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
264 if (BI != IntB.ranges.begin())
266 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
267 if (BI->valno == BValNo)
269 // When BValNo is null, we're looking for a dummy clobber-value for a subreg.
270 if (!BValNo && !BI->valno->isDefAccurate() && !BI->valno->getCopy())
272 if (BI->start <= AI->start && BI->end > AI->start)
274 if (BI->start > AI->start && BI->start < AI->end)
282 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
283 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
285 MachineOperand &MO = MI->getOperand(i);
286 if (MO.isReg() && MO.isImplicit())
287 NewMI->addOperand(MO);
291 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
292 /// IntA being the source and IntB being the dest, thus this defines a value
293 /// number in IntB. If the source value number (in IntA) is defined by a
294 /// commutable instruction and its other operand is coalesced to the copy dest
295 /// register, see if we can transform the copy into a noop by commuting the
296 /// definition. For example,
298 /// A3 = op A2 B0<kill>
300 /// B1 = A3 <- this copy
302 /// = op A3 <- more uses
306 /// B2 = op B0 A2<kill>
308 /// B1 = B2 <- now an identify copy
310 /// = op B2 <- more uses
312 /// This returns true if an interval was modified.
314 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
315 MachineInstr *CopyMI) {
316 // FIXME: For now, only eliminate the copy by commuting its def when the
317 // source register is a virtual register. We want to guard against cases
318 // where the copy is a back edge copy and commuting the def lengthen the
319 // live interval of the source register to the entire loop.
320 if (CP.isPhys() && CP.isFlipped())
323 // Bail if there is no dst interval.
324 if (!li_->hasInterval(CP.getDstReg()))
328 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 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
338 if (BLR == IntB.end()) return false;
339 VNInfo *BValNo = BLR->valno;
341 // Get the location that B is defined at. Two options: either this value has
342 // an unknown definition point or it is defined at CopyIdx. If unknown, we
344 if (!BValNo->getCopy()) return false;
345 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
347 // AValNo is the value number in A that defines the copy, A3 in the example.
348 LiveInterval::iterator ALR =
349 IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); //
351 assert(ALR != IntA.end() && "Live range not found!");
352 VNInfo *AValNo = ALR->valno;
353 // If other defs can reach uses of this def, then it's not safe to perform
354 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
356 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
357 AValNo->isUnused() || AValNo->hasPHIKill())
359 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
362 const TargetInstrDesc &TID = DefMI->getDesc();
363 if (!TID.isCommutable())
365 // If DefMI is a two-address instruction then commuting it will change the
366 // destination register.
367 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
368 assert(DefIdx != -1);
370 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
372 unsigned Op1, Op2, NewDstIdx;
373 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
377 else if (Op2 == UseOpIdx)
382 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
383 unsigned NewReg = NewDstMO.getReg();
384 if (NewReg != IntB.reg || !NewDstMO.isKill())
387 // Make sure there are no other definitions of IntB that would reach the
388 // uses which the new definition can reach.
389 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
392 // Abort if the aliases of IntB.reg have values that are not simply the
393 // clobbers from the superreg.
394 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
395 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
396 if (li_->hasInterval(*AS) &&
397 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
400 // If some of the uses of IntA.reg is already coalesced away, return false.
401 // It's not possible to determine whether it's safe to perform the coalescing.
402 for (MachineRegisterInfo::use_nodbg_iterator UI =
403 mri_->use_nodbg_begin(IntA.reg),
404 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
405 MachineInstr *UseMI = &*UI;
406 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
407 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
408 if (ULR == IntA.end())
410 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
414 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << *DefMI);
416 // At this point we have decided that it is legal to do this
417 // transformation. Start by commuting the instruction.
418 MachineBasicBlock *MBB = DefMI->getParent();
419 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
422 if (NewMI != DefMI) {
423 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
424 MBB->insert(DefMI, NewMI);
427 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
428 NewMI->getOperand(OpIdx).setIsKill();
430 bool BHasPHIKill = BValNo->hasPHIKill();
431 SmallVector<VNInfo*, 4> BDeadValNos;
432 std::map<SlotIndex, SlotIndex> BExtend;
434 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
442 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
444 BExtend[ALR->end] = BLR->end;
446 // Update uses of IntA of the specific Val# with IntB.
447 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
448 UE = mri_->use_end(); UI != UE;) {
449 MachineOperand &UseMO = UI.getOperand();
450 MachineInstr *UseMI = &*UI;
452 if (JoinedCopies.count(UseMI))
454 if (UseMI->isDebugValue()) {
455 // FIXME These don't have an instruction index. Not clear we have enough
456 // info to decide whether to do this replacement or not. For now do it.
457 UseMO.setReg(NewReg);
460 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
461 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
462 if (ULR == IntA.end() || ULR->valno != AValNo)
464 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
465 UseMO.substPhysReg(NewReg, *tri_);
467 UseMO.setReg(NewReg);
470 if (UseMO.isKill()) {
472 UseMO.setIsKill(false);
474 if (!UseMI->isCopy())
476 if (UseMI->getOperand(0).getReg() != IntB.reg ||
477 UseMI->getOperand(0).getSubReg())
480 // This copy will become a noop. If it's defining a new val#,
481 // remove that val# as well. However this live range is being
482 // extended to the end of the existing live range defined by the copy.
483 SlotIndex DefIdx = UseIdx.getDefIndex();
484 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
487 BHasPHIKill |= DLR->valno->hasPHIKill();
488 assert(DLR->valno->def == DefIdx);
489 BDeadValNos.push_back(DLR->valno);
490 BExtend[DLR->start] = DLR->end;
491 JoinedCopies.insert(UseMI);
494 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
495 // simply extend BLR if CopyMI doesn't end the range.
497 dbgs() << "Extending: ";
498 IntB.print(dbgs(), tri_);
501 // Remove val#'s defined by copies that will be coalesced away.
502 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
503 VNInfo *DeadVNI = BDeadValNos[i];
504 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
505 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS) {
506 if (!li_->hasInterval(*AS))
508 LiveInterval &ASLI = li_->getInterval(*AS);
509 if (const LiveRange *ASLR = ASLI.getLiveRangeContaining(DeadVNI->def))
510 ASLI.removeValNo(ASLR->valno);
513 IntB.removeValNo(BDeadValNos[i]);
516 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
518 VNInfo *ValNo = BValNo;
519 ValNo->def = AValNo->def;
521 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
523 if (AI->valno != AValNo) continue;
524 SlotIndex End = AI->end;
525 std::map<SlotIndex, SlotIndex>::iterator
526 EI = BExtend.find(End);
527 if (EI != BExtend.end())
529 IntB.addRange(LiveRange(AI->start, End, ValNo));
531 ValNo->setHasPHIKill(BHasPHIKill);
534 dbgs() << " result = ";
535 IntB.print(dbgs(), tri_);
536 dbgs() << "\nShortening: ";
537 IntA.print(dbgs(), tri_);
540 IntA.removeValNo(AValNo);
543 dbgs() << " result = ";
544 IntA.print(dbgs(), tri_);
552 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
553 /// fallthoughs to SuccMBB.
554 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
555 MachineBasicBlock *SuccMBB,
556 const TargetInstrInfo *tii_) {
559 MachineBasicBlock *TBB = 0, *FBB = 0;
560 SmallVector<MachineOperand, 4> Cond;
561 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
562 MBB->isSuccessor(SuccMBB);
565 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
566 /// from a physical register live interval as well as from the live intervals
567 /// of its sub-registers.
568 static void removeRange(LiveInterval &li,
569 SlotIndex Start, SlotIndex End,
570 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
571 li.removeRange(Start, End, true);
572 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
573 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
574 if (!li_->hasInterval(*SR))
576 LiveInterval &sli = li_->getInterval(*SR);
577 SlotIndex RemoveStart = Start;
578 SlotIndex RemoveEnd = Start;
580 while (RemoveEnd != End) {
581 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
584 RemoveEnd = (LR->end < End) ? LR->end : End;
585 sli.removeRange(RemoveStart, RemoveEnd, true);
586 RemoveStart = RemoveEnd;
592 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
593 /// as the copy instruction, trim the live interval to the last use and return
596 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
597 MachineBasicBlock *CopyMBB,
599 const LiveRange *LR) {
600 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
601 SlotIndex LastUseIdx;
602 MachineOperand *LastUse =
603 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
605 MachineInstr *LastUseMI = LastUse->getParent();
606 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
613 // r1025<dead> = r1024<kill>
614 if (MBBStart < LR->end)
615 removeRange(li, MBBStart, LR->end, li_, tri_);
619 // There are uses before the copy, just shorten the live range to the end
621 LastUse->setIsKill();
622 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
623 if (LastUseMI->isCopy()) {
624 MachineOperand &DefMO = LastUseMI->getOperand(0);
625 if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
632 if (LR->start <= MBBStart && LR->end > MBBStart) {
633 if (LR->start == li_->getZeroIndex()) {
634 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
635 // Live-in to the function but dead. Remove it from entry live-in set.
636 mf_->begin()->removeLiveIn(li.reg);
638 // FIXME: Shorten intervals in BBs that reaches this BB.
644 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
645 /// computation, replace the copy by rematerialize the definition.
646 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
649 MachineInstr *CopyMI) {
650 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
651 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
652 assert(SrcLR != SrcInt.end() && "Live range not found!");
653 VNInfo *ValNo = SrcLR->valno;
654 // If other defs can reach uses of this def, then it's not safe to perform
655 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
657 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
658 ValNo->isUnused() || ValNo->hasPHIKill())
660 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
661 assert(DefMI && "Defining instruction disappeared");
662 const TargetInstrDesc &TID = DefMI->getDesc();
663 if (!TID.isAsCheapAsAMove())
665 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
667 bool SawStore = false;
668 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
670 if (TID.getNumDefs() != 1)
672 if (!DefMI->isImplicitDef()) {
673 // Make sure the copy destination register class fits the instruction
674 // definition register class. The mismatch can happen as a result of earlier
675 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
676 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
677 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
678 if (mri_->getRegClass(DstReg) != RC)
680 } else if (!RC->contains(DstReg))
684 // If destination register has a sub-register index on it, make sure it mtches
685 // the instruction register class.
687 const TargetInstrDesc &TID = DefMI->getDesc();
688 if (TID.getNumDefs() != 1)
690 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
691 const TargetRegisterClass *DstSubRC =
692 DstRC->getSubRegisterRegClass(DstSubIdx);
693 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
696 else if (DefRC != DstSubRC)
700 RemoveCopyFlag(DstReg, CopyMI);
702 // If copy kills the source register, find the last use and propagate
704 bool checkForDeadDef = false;
705 MachineBasicBlock *MBB = CopyMI->getParent();
706 if (SrcLR->end == CopyIdx.getDefIndex())
707 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
708 checkForDeadDef = true;
711 MachineBasicBlock::iterator MII =
712 llvm::next(MachineBasicBlock::iterator(CopyMI));
713 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
714 MachineInstr *NewMI = prior(MII);
716 if (checkForDeadDef) {
717 // PR4090 fix: Trim interval failed because there was no use of the
718 // source interval in this MBB. If the def is in this MBB too then we
719 // should mark it dead:
720 if (DefMI->getParent() == MBB) {
721 DefMI->addRegisterDead(SrcInt.reg, tri_);
722 SrcLR->end = SrcLR->start.getNextSlot();
726 // CopyMI may have implicit operands, transfer them over to the newly
727 // rematerialized instruction. And update implicit def interval valnos.
728 for (unsigned i = CopyMI->getDesc().getNumOperands(),
729 e = CopyMI->getNumOperands(); i != e; ++i) {
730 MachineOperand &MO = CopyMI->getOperand(i);
731 if (MO.isReg() && MO.isImplicit())
732 NewMI->addOperand(MO);
734 RemoveCopyFlag(MO.getReg(), CopyMI);
737 TransferImplicitOps(CopyMI, NewMI);
738 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
739 CopyMI->eraseFromParent();
740 ReMatCopies.insert(CopyMI);
741 ReMatDefs.insert(DefMI);
742 DEBUG(dbgs() << "Remat: " << *NewMI);
747 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
748 /// update the subregister number if it is not zero. If DstReg is a
749 /// physical register and the existing subregister number of the def / use
750 /// being updated is not zero, make sure to set it to the correct physical
753 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
754 bool DstIsPhys = CP.isPhys();
755 unsigned SrcReg = CP.getSrcReg();
756 unsigned DstReg = CP.getDstReg();
757 unsigned SubIdx = CP.getSubIdx();
759 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
760 MachineInstr *UseMI = I.skipInstruction();) {
761 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
764 if (UseMI->isCopy() &&
765 !UseMI->getOperand(1).getSubReg() &&
766 !UseMI->getOperand(0).getSubReg() &&
767 UseMI->getOperand(1).getReg() == SrcReg &&
768 UseMI->getOperand(0).getReg() != SrcReg &&
769 UseMI->getOperand(0).getReg() != DstReg &&
770 !JoinedCopies.count(UseMI) &&
771 ReMaterializeTrivialDef(li_->getInterval(SrcReg),
772 UseMI->getOperand(0).getReg(), 0, UseMI))
776 SmallVector<unsigned,8> Ops;
778 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
779 bool Kills = false, Deads = false;
781 // Replace SrcReg with DstReg in all UseMI operands.
782 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
783 MachineOperand &MO = UseMI->getOperand(Ops[i]);
784 Kills |= MO.isKill();
785 Deads |= MO.isDead();
788 MO.substPhysReg(DstReg, *tri_);
790 MO.substVirtReg(DstReg, SubIdx, *tri_);
793 // This instruction is a copy that will be removed.
794 if (JoinedCopies.count(UseMI))
798 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
799 // read-modify-write of DstReg.
801 UseMI->addRegisterDead(DstReg, tri_);
802 else if (!Reads && Writes)
803 UseMI->addRegisterDefined(DstReg, tri_);
805 // Kill flags apply to the whole physical register.
806 if (DstIsPhys && Kills)
807 UseMI->addRegisterKilled(DstReg, tri_);
811 dbgs() << "\t\tupdated: ";
812 if (!UseMI->isDebugValue())
813 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
819 /// removeIntervalIfEmpty - Check if the live interval of a physical register
820 /// is empty, if so remove it and also remove the empty intervals of its
821 /// sub-registers. Return true if live interval is removed.
822 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
823 const TargetRegisterInfo *tri_) {
825 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
826 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
827 if (!li_->hasInterval(*SR))
829 LiveInterval &sli = li_->getInterval(*SR);
831 li_->removeInterval(*SR);
833 li_->removeInterval(li.reg);
839 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
840 /// Return true if live interval is removed.
841 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
842 MachineInstr *CopyMI) {
843 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
844 LiveInterval::iterator MLR =
845 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
847 return false; // Already removed by ShortenDeadCopySrcLiveRange.
848 SlotIndex RemoveStart = MLR->start;
849 SlotIndex RemoveEnd = MLR->end;
850 SlotIndex DefIdx = CopyIdx.getDefIndex();
851 // Remove the liverange that's defined by this.
852 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
853 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
854 return removeIntervalIfEmpty(li, li_, tri_);
859 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
860 /// the val# it defines. If the live interval becomes empty, remove it as well.
861 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
862 MachineInstr *DefMI) {
863 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
864 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
865 if (DefIdx != MLR->valno->def)
867 li.removeValNo(MLR->valno);
868 return removeIntervalIfEmpty(li, li_, tri_);
871 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
872 const MachineInstr *CopyMI) {
873 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
874 if (li_->hasInterval(DstReg)) {
875 LiveInterval &LI = li_->getInterval(DstReg);
876 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
877 if (LR->valno->getCopy() == CopyMI)
878 LR->valno->setCopy(0);
880 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
882 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
883 if (!li_->hasInterval(*AS))
885 LiveInterval &LI = li_->getInterval(*AS);
886 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
887 if (LR->valno->getCopy() == CopyMI)
888 LR->valno->setCopy(0);
892 /// PropagateDeadness - Propagate the dead marker to the instruction which
893 /// defines the val#.
894 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
895 SlotIndex &LRStart, LiveIntervals *li_,
896 const TargetRegisterInfo* tri_) {
897 MachineInstr *DefMI =
898 li_->getInstructionFromIndex(LRStart.getDefIndex());
899 if (DefMI && DefMI != CopyMI) {
900 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
902 DefMI->getOperand(DeadIdx).setIsDead();
904 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
905 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
906 LRStart = LRStart.getNextSlot();
910 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
911 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
912 /// ends the live range there. If there isn't another use, then this live range
913 /// is dead. Return true if live interval is removed.
915 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
916 MachineInstr *CopyMI) {
917 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
918 if (CopyIdx == SlotIndex()) {
919 // FIXME: special case: function live in. It can be a general case if the
920 // first instruction index starts at > 0 value.
921 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
922 // Live-in to the function but dead. Remove it from entry live-in set.
923 if (mf_->begin()->isLiveIn(li.reg))
924 mf_->begin()->removeLiveIn(li.reg);
925 if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
926 removeRange(li, LR->start, LR->end, li_, tri_);
927 return removeIntervalIfEmpty(li, li_, tri_);
930 LiveInterval::iterator LR =
931 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
933 // Livein but defined by a phi.
936 SlotIndex RemoveStart = LR->start;
937 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
938 if (LR->end > RemoveEnd)
939 // More uses past this copy? Nothing to do.
942 // If there is a last use in the same bb, we can't remove the live range.
943 // Shorten the live interval and return.
944 MachineBasicBlock *CopyMBB = CopyMI->getParent();
945 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
948 // There are other kills of the val#. Nothing to do.
949 if (!li.isOnlyLROfValNo(LR))
952 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
953 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
954 // If the live range starts in another mbb and the copy mbb is not a fall
955 // through mbb, then we can only cut the range from the beginning of the
957 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
959 if (LR->valno->def == RemoveStart) {
960 // If the def MI defines the val# and this copy is the only kill of the
961 // val#, then propagate the dead marker.
962 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
966 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
967 return removeIntervalIfEmpty(li, li_, tri_);
971 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
972 /// two virtual registers from different register classes.
974 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
976 const TargetRegisterClass *SrcRC,
977 const TargetRegisterClass *DstRC,
978 const TargetRegisterClass *NewRC) {
979 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
980 // This heuristics is good enough in practice, but it's obviously not *right*.
981 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
982 // out all but the most restrictive register classes.
983 if (NewRCCount > 4 ||
984 // Early exit if the function is fairly small, coalesce aggressively if
985 // that's the case. For really special register classes with 3 or
986 // fewer registers, be a bit more careful.
987 (li_->getFuncInstructionCount() / NewRCCount) < 8)
989 LiveInterval &SrcInt = li_->getInterval(SrcReg);
990 LiveInterval &DstInt = li_->getInterval(DstReg);
991 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
992 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
993 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
995 // Estimate *register use density*. If it doubles or more, abort.
996 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
997 mri_->use_nodbg_end());
998 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
999 mri_->use_nodbg_end());
1000 unsigned NewUses = SrcUses + DstUses;
1001 unsigned NewSize = SrcSize + DstSize;
1002 if (SrcRC != NewRC && SrcSize > NewRCCount) {
1003 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1004 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1007 if (DstRC != NewRC && DstSize > NewRCCount) {
1008 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1009 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1016 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1017 /// which are the src/dst of the copy instruction CopyMI. This returns true
1018 /// if the copy was successfully coalesced away. If it is not currently
1019 /// possible to coalesce this interval, but it may be possible if other
1020 /// things get coalesced, then it returns true by reference in 'Again'.
1021 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1022 MachineInstr *CopyMI = TheCopy.MI;
1025 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1026 return false; // Already done.
1028 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1030 CoalescerPair CP(*tii_, *tri_);
1031 if (!CP.setRegisters(CopyMI)) {
1032 DEBUG(dbgs() << "\tNot coalescable.\n");
1036 // If they are already joined we continue.
1037 if (CP.getSrcReg() == CP.getDstReg()) {
1038 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1039 return false; // Not coalescable.
1042 if (DisablePhysicalJoin && CP.isPhys()) {
1043 DEBUG(dbgs() << "\tPhysical joins disabled.\n");
1047 DEBUG(dbgs() << "\tConsidering merging %reg" << CP.getSrcReg());
1049 // Enforce policies.
1051 DEBUG(dbgs() <<" with physreg %" << tri_->getName(CP.getDstReg()) << "\n");
1052 // Only coalesce to allocatable physreg.
1053 if (!li_->isAllocatable(CP.getDstReg())) {
1054 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1055 return false; // Not coalescable.
1059 dbgs() << " with reg%" << CP.getDstReg();
1061 dbgs() << ":" << tri_->getSubRegIndexName(CP.getSubIdx());
1062 dbgs() << " to " << CP.getNewRC()->getName() << "\n";
1065 // Avoid constraining virtual register regclass too much.
1066 if (CP.isCrossClass()) {
1067 if (DisableCrossClassJoin) {
1068 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1071 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1072 mri_->getRegClass(CP.getSrcReg()),
1073 mri_->getRegClass(CP.getDstReg()),
1075 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1076 << CP.getNewRC()->getName() << ".\n");
1077 Again = true; // May be possible to coalesce later.
1082 // When possible, let DstReg be the larger interval.
1083 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1084 li_->getInterval(CP.getDstReg()).ranges.size())
1088 // We need to be careful about coalescing a source physical register with a
1089 // virtual register. Once the coalescing is done, it cannot be broken and
1090 // these are not spillable! If the destination interval uses are far away,
1091 // think twice about coalescing them!
1092 // FIXME: Why are we skipping this test for partial copies?
1093 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1094 if (!CP.isPartial() && CP.isPhys()) {
1095 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1097 // Don't join with physregs that have a ridiculous number of live
1098 // ranges. The data structure performance is really bad when that
1100 if (li_->hasInterval(CP.getDstReg()) &&
1101 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1104 << "\tPhysical register live interval too complicated, abort!\n");
1108 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1109 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1110 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1111 if (Length > Threshold &&
1112 std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1113 mri_->use_nodbg_end()) * Threshold < Length) {
1114 // Before giving up coalescing, if definition of source is defined by
1115 // trivial computation, try rematerializing it.
1116 if (!CP.isFlipped() &&
1117 ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1121 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1122 Again = true; // May be possible to coalesce later.
1127 // Okay, attempt to join these two intervals. On failure, this returns false.
1128 // Otherwise, if one of the intervals being joined is a physreg, this method
1129 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1130 // been modified, so we can use this information below to update aliases.
1131 if (!JoinIntervals(CP)) {
1132 // Coalescing failed.
1134 // If definition of source is defined by trivial computation, try
1135 // rematerializing it.
1136 if (!CP.isFlipped() &&
1137 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1138 CP.getDstReg(), 0, CopyMI))
1141 // If we can eliminate the copy without merging the live ranges, do so now.
1142 if (!CP.isPartial()) {
1143 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1144 RemoveCopyByCommutingDef(CP, CopyMI)) {
1145 JoinedCopies.insert(CopyMI);
1146 DEBUG(dbgs() << "\tTrivial!\n");
1151 // Otherwise, we are unable to join the intervals.
1152 DEBUG(dbgs() << "\tInterference!\n");
1153 Again = true; // May be possible to coalesce later.
1157 // Coalescing to a virtual register that is of a sub-register class of the
1158 // other. Make sure the resulting register is set to the right register class.
1159 if (CP.isCrossClass()) {
1161 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1164 // Remember to delete the copy instruction.
1165 JoinedCopies.insert(CopyMI);
1167 UpdateRegDefsUses(CP);
1169 // If we have extended the live range of a physical register, make sure we
1170 // update live-in lists as well.
1172 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1173 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1174 // ranges for this, and they are preserved.
1175 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1176 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1178 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1179 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1180 MachineBasicBlock &block = *BlockSeq[idx];
1181 if (!block.isLiveIn(CP.getDstReg()))
1182 block.addLiveIn(CP.getDstReg());
1188 // SrcReg is guarateed to be the register whose live interval that is
1190 li_->removeInterval(CP.getSrcReg());
1192 // Update regalloc hint.
1193 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1196 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1197 dbgs() << "\tJoined. Result = ";
1198 DstInt.print(dbgs(), tri_);
1206 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1207 /// compute what the resultant value numbers for each value in the input two
1208 /// ranges will be. This is complicated by copies between the two which can
1209 /// and will commonly cause multiple value numbers to be merged into one.
1211 /// VN is the value number that we're trying to resolve. InstDefiningValue
1212 /// keeps track of the new InstDefiningValue assignment for the result
1213 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1214 /// whether a value in this or other is a copy from the opposite set.
1215 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1216 /// already been assigned.
1218 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1219 /// contains the value number the copy is from.
1221 static unsigned ComputeUltimateVN(VNInfo *VNI,
1222 SmallVector<VNInfo*, 16> &NewVNInfo,
1223 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1224 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1225 SmallVector<int, 16> &ThisValNoAssignments,
1226 SmallVector<int, 16> &OtherValNoAssignments) {
1227 unsigned VN = VNI->id;
1229 // If the VN has already been computed, just return it.
1230 if (ThisValNoAssignments[VN] >= 0)
1231 return ThisValNoAssignments[VN];
1232 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1234 // If this val is not a copy from the other val, then it must be a new value
1235 // number in the destination.
1236 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1237 if (I == ThisFromOther.end()) {
1238 NewVNInfo.push_back(VNI);
1239 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1241 VNInfo *OtherValNo = I->second;
1243 // Otherwise, this *is* a copy from the RHS. If the other side has already
1244 // been computed, return it.
1245 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1246 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1248 // Mark this value number as currently being computed, then ask what the
1249 // ultimate value # of the other value is.
1250 ThisValNoAssignments[VN] = -2;
1251 unsigned UltimateVN =
1252 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1253 OtherValNoAssignments, ThisValNoAssignments);
1254 return ThisValNoAssignments[VN] = UltimateVN;
1257 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1259 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1260 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1261 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1263 // If a live interval is a physical register, check for interference with any
1264 // aliases. The interference check implemented here is a bit more conservative
1265 // than the full interfeence check below. We allow overlapping live ranges
1266 // only when one is a copy of the other.
1268 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1269 if (!li_->hasInterval(*AS))
1271 const LiveInterval &LHS = li_->getInterval(*AS);
1272 LiveInterval::const_iterator LI = LHS.begin();
1273 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1275 LI = std::lower_bound(LI, LHS.end(), RI->start);
1276 // Does LHS have an overlapping live range starting before RI?
1277 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1278 (RI->start != RI->valno->def ||
1279 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1281 dbgs() << "\t\tInterference from alias: ";
1282 LHS.print(dbgs(), tri_);
1283 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1288 // Check that LHS ranges beginning in this range are copies.
1289 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1290 if (LI->start != LI->valno->def ||
1291 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1293 dbgs() << "\t\tInterference from alias: ";
1294 LHS.print(dbgs(), tri_);
1295 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1304 // Compute the final value assignment, assuming that the live ranges can be
1306 SmallVector<int, 16> LHSValNoAssignments;
1307 SmallVector<int, 16> RHSValNoAssignments;
1308 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1309 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1310 SmallVector<VNInfo*, 16> NewVNInfo;
1312 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1313 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1315 // Loop over the value numbers of the LHS, seeing if any are defined from
1317 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1320 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
1323 // Never join with a register that has EarlyClobber redefs.
1324 if (VNI->hasRedefByEC())
1327 // DstReg is known to be a register in the LHS interval. If the src is
1328 // from the RHS interval, we can use its value #.
1329 if (!CP.isCoalescable(VNI->getCopy()))
1332 // Figure out the value # from the RHS.
1333 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1334 // The copy could be to an aliased physreg.
1336 LHSValsDefinedFromRHS[VNI] = lr->valno;
1339 // Loop over the value numbers of the RHS, seeing if any are defined from
1341 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1344 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
1347 // Never join with a register that has EarlyClobber redefs.
1348 if (VNI->hasRedefByEC())
1351 // DstReg is known to be a register in the RHS interval. If the src is
1352 // from the LHS interval, we can use its value #.
1353 if (!CP.isCoalescable(VNI->getCopy()))
1356 // Figure out the value # from the LHS.
1357 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1358 // The copy could be to an aliased physreg.
1360 RHSValsDefinedFromLHS[VNI] = lr->valno;
1363 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1364 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1365 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1367 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1370 unsigned VN = VNI->id;
1371 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1373 ComputeUltimateVN(VNI, NewVNInfo,
1374 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1375 LHSValNoAssignments, RHSValNoAssignments);
1377 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1380 unsigned VN = VNI->id;
1381 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1383 // If this value number isn't a copy from the LHS, it's a new number.
1384 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1385 NewVNInfo.push_back(VNI);
1386 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1390 ComputeUltimateVN(VNI, NewVNInfo,
1391 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1392 RHSValNoAssignments, LHSValNoAssignments);
1395 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1396 // interval lists to see if these intervals are coalescable.
1397 LiveInterval::const_iterator I = LHS.begin();
1398 LiveInterval::const_iterator IE = LHS.end();
1399 LiveInterval::const_iterator J = RHS.begin();
1400 LiveInterval::const_iterator JE = RHS.end();
1402 // Skip ahead until the first place of potential sharing.
1403 if (I != IE && J != JE) {
1404 if (I->start < J->start) {
1405 I = std::upper_bound(I, IE, J->start);
1406 if (I != LHS.begin()) --I;
1407 } else if (J->start < I->start) {
1408 J = std::upper_bound(J, JE, I->start);
1409 if (J != RHS.begin()) --J;
1413 while (I != IE && J != JE) {
1414 // Determine if these two live ranges overlap.
1416 if (I->start < J->start) {
1417 Overlaps = I->end > J->start;
1419 Overlaps = J->end > I->start;
1422 // If so, check value # info to determine if they are really different.
1424 // If the live range overlap will map to the same value number in the
1425 // result liverange, we can still coalesce them. If not, we can't.
1426 if (LHSValNoAssignments[I->valno->id] !=
1427 RHSValNoAssignments[J->valno->id])
1429 // If it's re-defined by an early clobber somewhere in the live range,
1430 // then conservatively abort coalescing.
1431 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1435 if (I->end < J->end)
1441 // Update kill info. Some live ranges are extended due to copy coalescing.
1442 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1443 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1444 VNInfo *VNI = I->first;
1445 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1446 if (VNI->hasPHIKill())
1447 NewVNInfo[LHSValID]->setHasPHIKill(true);
1450 // Update kill info. Some live ranges are extended due to copy coalescing.
1451 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1452 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1453 VNInfo *VNI = I->first;
1454 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1455 if (VNI->hasPHIKill())
1456 NewVNInfo[RHSValID]->setHasPHIKill(true);
1459 if (LHSValNoAssignments.empty())
1460 LHSValNoAssignments.push_back(-1);
1461 if (RHSValNoAssignments.empty())
1462 RHSValNoAssignments.push_back(-1);
1464 // If we get here, we know that we can coalesce the live ranges. Ask the
1465 // intervals to coalesce themselves now.
1466 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1472 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1473 // depth of the basic block (the unsigned), and then on the MBB number.
1474 struct DepthMBBCompare {
1475 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1476 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1477 // Deeper loops first
1478 if (LHS.first != RHS.first)
1479 return LHS.first > RHS.first;
1481 // Prefer blocks that are more connected in the CFG. This takes care of
1482 // the most difficult copies first while intervals are short.
1483 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1484 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1488 // As a last resort, sort by block number.
1489 return LHS.second->getNumber() < RHS.second->getNumber();
1494 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1495 std::vector<CopyRec> &TryAgain) {
1496 DEBUG(dbgs() << MBB->getName() << ":\n");
1498 std::vector<CopyRec> VirtCopies;
1499 std::vector<CopyRec> PhysCopies;
1500 std::vector<CopyRec> ImpDefCopies;
1501 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1503 MachineInstr *Inst = MII++;
1505 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1506 unsigned SrcReg, DstReg;
1507 if (Inst->isCopy()) {
1508 DstReg = Inst->getOperand(0).getReg();
1509 SrcReg = Inst->getOperand(1).getReg();
1510 } else if (Inst->isSubregToReg()) {
1511 DstReg = Inst->getOperand(0).getReg();
1512 SrcReg = Inst->getOperand(2).getReg();
1516 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1517 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1518 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1519 ImpDefCopies.push_back(CopyRec(Inst, 0));
1520 else if (SrcIsPhys || DstIsPhys)
1521 PhysCopies.push_back(CopyRec(Inst, 0));
1523 VirtCopies.push_back(CopyRec(Inst, 0));
1526 // Try coalescing implicit copies and insert_subreg <undef> first,
1527 // followed by copies to / from physical registers, then finally copies
1528 // from virtual registers to virtual registers.
1529 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1530 CopyRec &TheCopy = ImpDefCopies[i];
1532 if (!JoinCopy(TheCopy, Again))
1534 TryAgain.push_back(TheCopy);
1536 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1537 CopyRec &TheCopy = PhysCopies[i];
1539 if (!JoinCopy(TheCopy, Again))
1541 TryAgain.push_back(TheCopy);
1543 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1544 CopyRec &TheCopy = VirtCopies[i];
1546 if (!JoinCopy(TheCopy, Again))
1548 TryAgain.push_back(TheCopy);
1552 void SimpleRegisterCoalescing::joinIntervals() {
1553 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1555 std::vector<CopyRec> TryAgainList;
1556 if (loopInfo->empty()) {
1557 // If there are no loops in the function, join intervals in function order.
1558 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1560 CopyCoalesceInMBB(I, TryAgainList);
1562 // Otherwise, join intervals in inner loops before other intervals.
1563 // Unfortunately we can't just iterate over loop hierarchy here because
1564 // there may be more MBB's than BB's. Collect MBB's for sorting.
1566 // Join intervals in the function prolog first. We want to join physical
1567 // registers with virtual registers before the intervals got too long.
1568 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1569 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1570 MachineBasicBlock *MBB = I;
1571 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1574 // Sort by loop depth.
1575 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1577 // Finally, join intervals in loop nest order.
1578 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1579 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1582 // Joining intervals can allow other intervals to be joined. Iteratively join
1583 // until we make no progress.
1584 bool ProgressMade = true;
1585 while (ProgressMade) {
1586 ProgressMade = false;
1588 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1589 CopyRec &TheCopy = TryAgainList[i];
1594 bool Success = JoinCopy(TheCopy, Again);
1595 if (Success || !Again) {
1596 TheCopy.MI = 0; // Mark this one as done.
1597 ProgressMade = true;
1603 /// Return true if the two specified registers belong to different register
1604 /// classes. The registers may be either phys or virt regs.
1606 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1607 unsigned RegB) const {
1608 // Get the register classes for the first reg.
1609 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1610 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1611 "Shouldn't consider two physregs!");
1612 return !mri_->getRegClass(RegB)->contains(RegA);
1615 // Compare against the regclass for the second reg.
1616 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1617 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1618 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1619 return RegClassA != RegClassB;
1621 return !RegClassA->contains(RegB);
1624 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1625 /// between cycles Start and End or NULL if there are no uses.
1627 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1630 SlotIndex &UseIdx) const{
1631 UseIdx = SlotIndex();
1632 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1633 MachineOperand *LastUse = NULL;
1634 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1635 E = mri_->use_nodbg_end(); I != E; ++I) {
1636 MachineOperand &Use = I.getOperand();
1637 MachineInstr *UseMI = Use.getParent();
1638 if (UseMI->isIdentityCopy())
1640 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1641 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1642 // that compares higher than any other interval.
1643 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1645 UseIdx = Idx.getUseIndex();
1651 SlotIndex s = Start;
1652 SlotIndex e = End.getPrevSlot().getBaseIndex();
1654 // Skip deleted instructions
1655 MachineInstr *MI = li_->getInstructionFromIndex(e);
1656 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1657 e = e.getPrevIndex();
1658 MI = li_->getInstructionFromIndex(e);
1660 if (e < s || MI == NULL)
1663 // Ignore identity copies.
1664 if (!MI->isIdentityCopy())
1665 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1666 MachineOperand &Use = MI->getOperand(i);
1667 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1668 tri_->regsOverlap(Use.getReg(), Reg)) {
1669 UseIdx = e.getUseIndex();
1674 e = e.getPrevIndex();
1680 void SimpleRegisterCoalescing::releaseMemory() {
1681 JoinedCopies.clear();
1682 ReMatCopies.clear();
1686 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1688 mri_ = &fn.getRegInfo();
1689 tm_ = &fn.getTarget();
1690 tri_ = tm_->getRegisterInfo();
1691 tii_ = tm_->getInstrInfo();
1692 li_ = &getAnalysis<LiveIntervals>();
1693 AA = &getAnalysis<AliasAnalysis>();
1694 loopInfo = &getAnalysis<MachineLoopInfo>();
1696 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1697 << "********** Function: "
1698 << ((Value*)mf_->getFunction())->getName() << '\n');
1700 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1701 E = tri_->regclass_end(); I != E; ++I)
1702 allocatableRCRegs_.insert(std::make_pair(*I,
1703 tri_->getAllocatableSet(fn, *I)));
1705 // Join (coalesce) intervals if requested.
1706 if (EnableJoining) {
1709 dbgs() << "********** INTERVALS POST JOINING **********\n";
1710 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1712 I->second->print(dbgs(), tri_);
1718 // Perform a final pass over the instructions and compute spill weights
1719 // and remove identity moves.
1720 SmallVector<unsigned, 4> DeadDefs;
1721 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1722 mbbi != mbbe; ++mbbi) {
1723 MachineBasicBlock* mbb = mbbi;
1724 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1726 MachineInstr *MI = mii;
1727 if (JoinedCopies.count(MI)) {
1728 // Delete all coalesced copies.
1729 bool DoDelete = true;
1730 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1731 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1732 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1733 MI->getNumOperands() > 2)
1734 // Do not delete extract_subreg, insert_subreg of physical
1735 // registers unless the definition is dead. e.g.
1736 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1737 // or else the scavenger may complain. LowerSubregs will
1738 // delete them later.
1741 if (MI->allDefsAreDead()) {
1742 LiveInterval &li = li_->getInterval(SrcReg);
1743 if (!ShortenDeadCopySrcLiveRange(li, MI))
1744 ShortenDeadCopyLiveRange(li, MI);
1748 // We need the instruction to adjust liveness, so make it a KILL.
1749 if (MI->isSubregToReg()) {
1750 MI->RemoveOperand(3);
1751 MI->RemoveOperand(1);
1753 MI->setDesc(tii_->get(TargetOpcode::KILL));
1754 mii = llvm::next(mii);
1756 li_->RemoveMachineInstrFromMaps(MI);
1757 mii = mbbi->erase(mii);
1763 // Now check if this is a remat'ed def instruction which is now dead.
1764 if (ReMatDefs.count(MI)) {
1766 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1767 const MachineOperand &MO = MI->getOperand(i);
1770 unsigned Reg = MO.getReg();
1773 if (TargetRegisterInfo::isVirtualRegister(Reg))
1774 DeadDefs.push_back(Reg);
1777 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1778 !mri_->use_nodbg_empty(Reg)) {
1784 while (!DeadDefs.empty()) {
1785 unsigned DeadDef = DeadDefs.back();
1786 DeadDefs.pop_back();
1787 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1789 li_->RemoveMachineInstrFromMaps(mii);
1790 mii = mbbi->erase(mii);
1796 // If the move will be an identity move delete it
1797 if (MI->isIdentityCopy()) {
1798 unsigned SrcReg = MI->getOperand(1).getReg();
1799 if (li_->hasInterval(SrcReg)) {
1800 LiveInterval &RegInt = li_->getInterval(SrcReg);
1801 // If def of this move instruction is dead, remove its live range
1802 // from the destination register's live interval.
1803 if (MI->allDefsAreDead()) {
1804 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1805 ShortenDeadCopyLiveRange(RegInt, MI);
1808 li_->RemoveMachineInstrFromMaps(MI);
1809 mii = mbbi->erase(mii);
1816 // Check for now unnecessary kill flags.
1817 if (li_->isNotInMIMap(MI)) continue;
1818 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1819 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1820 MachineOperand &MO = MI->getOperand(i);
1821 if (!MO.isReg() || !MO.isKill()) continue;
1822 unsigned reg = MO.getReg();
1823 if (!reg || !li_->hasInterval(reg)) continue;
1824 if (!li_->getInterval(reg).killedAt(DefIdx))
1825 MO.setIsKill(false);
1834 /// print - Implement the dump method.
1835 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1839 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1840 return new SimpleRegisterCoalescing();
1843 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1844 DEFINING_FILE_FOR(SimpleRegisterCoalescing)