1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
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 the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "LiveDebugVariables.h"
19 #include "RegisterClassInfo.h"
20 #include "VirtRegMap.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Value.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/OwningPtr.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/STLExtras.h"
51 STATISTIC(numJoins , "Number of interval joins performed");
52 STATISTIC(numCrossRCs , "Number of cross class joins performed");
53 STATISTIC(numCommutes , "Number of instruction commuting performed");
54 STATISTIC(numExtends , "Number of copies extended");
55 STATISTIC(NumReMats , "Number of instructions re-materialized");
56 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
57 STATISTIC(numAborts , "Number of times interval joining aborted");
58 STATISTIC(NumInflated , "Number of register classes inflated");
61 EnableJoining("join-liveintervals",
62 cl::desc("Coalesce copies (default=true)"),
66 DisableCrossClassJoin("disable-cross-class-join",
67 cl::desc("Avoid coalescing cross register class copies"),
68 cl::init(false), cl::Hidden);
71 EnablePhysicalJoin("join-physregs",
72 cl::desc("Join physical register copies"),
73 cl::init(false), cl::Hidden);
76 VerifyCoalescing("verify-coalescing",
77 cl::desc("Verify machine instrs before and after register coalescing"),
81 class RegisterCoalescer : public MachineFunctionPass {
83 MachineRegisterInfo* MRI;
84 const TargetMachine* TM;
85 const TargetRegisterInfo* TRI;
86 const TargetInstrInfo* TII;
88 LiveDebugVariables *LDV;
89 const MachineLoopInfo* Loops;
91 RegisterClassInfo RegClassInfo;
93 /// JoinedCopies - Keep track of copies eliminated due to coalescing.
95 SmallPtrSet<MachineInstr*, 32> JoinedCopies;
97 /// ReMatCopies - Keep track of copies eliminated due to remat.
99 SmallPtrSet<MachineInstr*, 32> ReMatCopies;
101 /// ReMatDefs - Keep track of definition instructions which have
103 SmallPtrSet<MachineInstr*, 8> ReMatDefs;
105 /// joinIntervals - join compatible live intervals
106 void joinIntervals();
108 /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting
109 /// copies that cannot yet be coalesced into the "TryAgain" list.
110 void CopyCoalesceInMBB(MachineBasicBlock *MBB,
111 std::vector<MachineInstr*> &TryAgain);
113 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
114 /// which are the src/dst of the copy instruction CopyMI. This returns
115 /// true if the copy was successfully coalesced away. If it is not
116 /// currently possible to coalesce this interval, but it may be possible if
117 /// other things get coalesced, then it returns true by reference in
119 bool JoinCopy(MachineInstr *TheCopy, bool &Again);
121 /// JoinIntervals - Attempt to join these two intervals. On failure, this
122 /// returns false. The output "SrcInt" will not have been modified, so we
123 /// can use this information below to update aliases.
124 bool JoinIntervals(CoalescerPair &CP);
126 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
127 /// the source value number is defined by a copy from the destination reg
128 /// see if we can merge these two destination reg valno# into a single
129 /// value number, eliminating a copy.
130 bool AdjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
132 /// HasOtherReachingDefs - Return true if there are definitions of IntB
133 /// other than BValNo val# that can reach uses of AValno val# of IntA.
134 bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
135 VNInfo *AValNo, VNInfo *BValNo);
137 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy.
138 /// If the source value number is defined by a commutable instruction and
139 /// its other operand is coalesced to the copy dest register, see if we
140 /// can transform the copy into a noop by commuting the definition.
141 bool RemoveCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
143 /// ReMaterializeTrivialDef - If the source of a copy is defined by a
144 /// trivial computation, replace the copy by rematerialize the definition.
145 /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
146 bool ReMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
147 unsigned DstReg, MachineInstr *CopyMI);
149 /// shouldJoinPhys - Return true if a physreg copy should be joined.
150 bool shouldJoinPhys(CoalescerPair &CP);
152 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
153 /// two virtual registers from different register classes.
154 bool isWinToJoinCrossClass(unsigned SrcReg,
156 const TargetRegisterClass *SrcRC,
157 const TargetRegisterClass *DstRC,
158 const TargetRegisterClass *NewRC);
160 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
161 /// update the subregister number if it is not zero. If DstReg is a
162 /// physical register and the existing subregister number of the def / use
163 /// being updated is not zero, make sure to set it to the correct physical
165 void UpdateRegDefsUses(const CoalescerPair &CP);
167 /// RemoveDeadDef - If a def of a live interval is now determined dead,
168 /// remove the val# it defines. If the live interval becomes empty, remove
170 bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
172 /// RemoveCopyFlag - If DstReg is no longer defined by CopyMI, clear the
173 /// VNInfo copy flag for DstReg and all aliases.
174 void RemoveCopyFlag(unsigned DstReg, const MachineInstr *CopyMI);
176 /// markAsJoined - Remember that CopyMI has already been joined.
177 void markAsJoined(MachineInstr *CopyMI);
179 /// eliminateUndefCopy - Handle copies of undef values.
180 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
183 static char ID; // Class identification, replacement for typeinfo
184 RegisterCoalescer() : MachineFunctionPass(ID) {
185 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
188 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
190 virtual void releaseMemory();
192 /// runOnMachineFunction - pass entry point
193 virtual bool runOnMachineFunction(MachineFunction&);
195 /// print - Implement the dump method.
196 virtual void print(raw_ostream &O, const Module* = 0) const;
198 } /// end anonymous namespace
200 char &llvm::RegisterCoalescerPassID = RegisterCoalescer::ID;
202 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
203 "Simple Register Coalescing", false, false)
204 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
205 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
206 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
207 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
208 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
209 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
210 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
211 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
212 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
213 "Simple Register Coalescing", false, false)
215 char RegisterCoalescer::ID = 0;
217 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
220 return tri.composeSubRegIndices(a, b);
223 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
224 unsigned &Src, unsigned &Dst,
225 unsigned &SrcSub, unsigned &DstSub) {
227 Dst = MI->getOperand(0).getReg();
228 DstSub = MI->getOperand(0).getSubReg();
229 Src = MI->getOperand(1).getReg();
230 SrcSub = MI->getOperand(1).getSubReg();
231 } else if (MI->isSubregToReg()) {
232 Dst = MI->getOperand(0).getReg();
233 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
234 MI->getOperand(3).getImm());
235 Src = MI->getOperand(2).getReg();
236 SrcSub = MI->getOperand(2).getSubReg();
242 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
243 SrcReg = DstReg = SubIdx = 0;
245 Flipped = CrossClass = false;
247 unsigned Src, Dst, SrcSub, DstSub;
248 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
250 Partial = SrcSub || DstSub;
252 // If one register is a physreg, it must be Dst.
253 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
254 if (TargetRegisterInfo::isPhysicalRegister(Dst))
257 std::swap(SrcSub, DstSub);
261 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
263 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
264 // Eliminate DstSub on a physreg.
266 Dst = TRI.getSubReg(Dst, DstSub);
267 if (!Dst) return false;
271 // Eliminate SrcSub by picking a corresponding Dst superregister.
273 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
274 if (!Dst) return false;
276 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
280 // Both registers are virtual.
282 // Both registers have subreg indices.
283 if (SrcSub && DstSub) {
284 // For now we only handle the case of identical indices in commensurate
285 // registers: Dreg:ssub_1 + Dreg:ssub_1 -> Dreg
286 // FIXME: Handle Qreg:ssub_3 + Dreg:ssub_1 as QReg:dsub_1 + Dreg.
287 if (SrcSub != DstSub)
289 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
290 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
291 if (!TRI.getCommonSubClass(DstRC, SrcRC))
296 // There can be no SrcSub.
301 assert(!Flipped && "Unexpected flip");
305 // Find the new register class.
306 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
307 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
309 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
311 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
314 CrossClass = NewRC != DstRC || NewRC != SrcRC;
316 // Check our invariants
317 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
318 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
319 "Cannot have a physical SubIdx");
326 bool CoalescerPair::flip() {
327 if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg))
329 std::swap(SrcReg, DstReg);
334 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
337 unsigned Src, Dst, SrcSub, DstSub;
338 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
341 // Find the virtual register that is SrcReg.
344 std::swap(SrcSub, DstSub);
345 } else if (Src != SrcReg) {
349 // Now check that Dst matches DstReg.
350 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
351 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
353 assert(!SubIdx && "Inconsistent CoalescerPair state.");
354 // DstSub could be set for a physreg from INSERT_SUBREG.
356 Dst = TRI.getSubReg(Dst, DstSub);
359 return DstReg == Dst;
360 // This is a partial register copy. Check that the parts match.
361 return TRI.getSubReg(DstReg, SrcSub) == Dst;
363 // DstReg is virtual.
366 // Registers match, do the subregisters line up?
367 return compose(TRI, SubIdx, SrcSub) == DstSub;
371 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
372 AU.setPreservesCFG();
373 AU.addRequired<AliasAnalysis>();
374 AU.addRequired<LiveIntervals>();
375 AU.addPreserved<LiveIntervals>();
376 AU.addRequired<LiveDebugVariables>();
377 AU.addPreserved<LiveDebugVariables>();
378 AU.addPreserved<SlotIndexes>();
379 AU.addRequired<MachineLoopInfo>();
380 AU.addPreserved<MachineLoopInfo>();
381 AU.addPreservedID(MachineDominatorsID);
382 AU.addPreservedID(StrongPHIEliminationID);
383 AU.addPreservedID(PHIEliminationID);
384 AU.addPreservedID(TwoAddressInstructionPassID);
385 MachineFunctionPass::getAnalysisUsage(AU);
388 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
389 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
390 JoinedCopies.insert(CopyMI);
392 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
393 /// code elimination.
394 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
395 E = CopyMI->operands_end(); I != E; ++I)
400 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
401 /// being the source and IntB being the dest, thus this defines a value number
402 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
403 /// see if we can merge these two pieces of B into a single value number,
404 /// eliminating a copy. For example:
408 /// B1 = A3 <- this copy
410 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
411 /// value number to be replaced with B0 (which simplifies the B liveinterval).
413 /// This returns true if an interval was modified.
415 bool RegisterCoalescer::AdjustCopiesBackFrom(const CoalescerPair &CP,
416 MachineInstr *CopyMI) {
417 // Bail if there is no dst interval - can happen when merging physical subreg
419 if (!LIS->hasInterval(CP.getDstReg()))
423 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
425 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
426 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
428 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
429 // the example above.
430 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
431 if (BLR == IntB.end()) return false;
432 VNInfo *BValNo = BLR->valno;
434 // Get the location that B is defined at. Two options: either this value has
435 // an unknown definition point or it is defined at CopyIdx. If unknown, we
437 if (!BValNo->isDefByCopy()) return false;
438 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
440 // AValNo is the value number in A that defines the copy, A3 in the example.
441 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
442 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
443 // The live range might not exist after fun with physreg coalescing.
444 if (ALR == IntA.end()) return false;
445 VNInfo *AValNo = ALR->valno;
446 // If it's re-defined by an early clobber somewhere in the live range, then
447 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
449 // 172 %ECX<def> = MOV32rr %reg1039<kill>
450 // 180 INLINEASM <es:subl $5,$1
451 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
453 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
454 // 188 %EAX<def> = MOV32rr %EAX<kill>
455 // 196 %ECX<def> = MOV32rr %ECX<kill>
456 // 204 %ECX<def> = MOV32rr %ECX<kill>
457 // 212 %EAX<def> = MOV32rr %EAX<kill>
458 // 220 %EAX<def> = MOV32rr %EAX
459 // 228 %reg1039<def> = MOV32rr %ECX<kill>
460 // The early clobber operand ties ECX input to the ECX def.
462 // The live interval of ECX is represented as this:
463 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
464 // The coalescer has no idea there was a def in the middle of [174,230].
465 if (AValNo->hasRedefByEC())
468 // If AValNo is defined as a copy from IntB, we can potentially process this.
469 // Get the instruction that defines this value number.
470 if (!CP.isCoalescable(AValNo->getCopy()))
473 // Get the LiveRange in IntB that this value number starts with.
474 LiveInterval::iterator ValLR =
475 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
476 if (ValLR == IntB.end())
479 // Make sure that the end of the live range is inside the same block as
481 MachineInstr *ValLREndInst =
482 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
483 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
486 // Okay, we now know that ValLR ends in the same block that the CopyMI
487 // live-range starts. If there are no intervening live ranges between them in
488 // IntB, we can merge them.
489 if (ValLR+1 != BLR) return false;
491 // If a live interval is a physical register, conservatively check if any
492 // of its aliases is overlapping the live interval of the virtual register.
493 // If so, do not coalesce.
494 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
495 for (const unsigned *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
496 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
498 dbgs() << "\t\tInterfere with alias ";
499 LIS->getInterval(*AS).print(dbgs(), TRI);
506 dbgs() << "Extending: ";
507 IntB.print(dbgs(), TRI);
510 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
511 // We are about to delete CopyMI, so need to remove it as the 'instruction
512 // that defines this value #'. Update the valnum with the new defining
514 BValNo->def = FillerStart;
517 // Okay, we can merge them. We need to insert a new liverange:
518 // [ValLR.end, BLR.begin) of either value number, then we merge the
519 // two value numbers.
520 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
522 // If the IntB live range is assigned to a physical register, and if that
523 // physreg has sub-registers, update their live intervals as well.
524 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
525 for (const unsigned *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
526 if (!LIS->hasInterval(*SR))
528 LiveInterval &SRLI = LIS->getInterval(*SR);
529 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
530 SRLI.getNextValue(FillerStart, 0,
531 LIS->getVNInfoAllocator())));
535 // Okay, merge "B1" into the same value number as "B0".
536 if (BValNo != ValLR->valno) {
537 // If B1 is killed by a PHI, then the merged live range must also be killed
538 // by the same PHI, as B0 and B1 can not overlap.
539 bool HasPHIKill = BValNo->hasPHIKill();
540 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
542 ValLR->valno->setHasPHIKill(true);
545 dbgs() << " result = ";
546 IntB.print(dbgs(), TRI);
550 // If the source instruction was killing the source register before the
551 // merge, unset the isKill marker given the live range has been extended.
552 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
554 ValLREndInst->getOperand(UIdx).setIsKill(false);
557 // If the copy instruction was killing the destination register before the
558 // merge, find the last use and trim the live range. That will also add the
560 if (ALR->end == CopyIdx)
561 LIS->shrinkToUses(&IntA);
567 /// HasOtherReachingDefs - Return true if there are definitions of IntB
568 /// other than BValNo val# that can reach uses of AValno val# of IntA.
569 bool RegisterCoalescer::HasOtherReachingDefs(LiveInterval &IntA,
573 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
575 if (AI->valno != AValNo) continue;
576 LiveInterval::Ranges::iterator BI =
577 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
578 if (BI != IntB.ranges.begin())
580 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
581 if (BI->valno == BValNo)
583 if (BI->start <= AI->start && BI->end > AI->start)
585 if (BI->start > AI->start && BI->start < AI->end)
592 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
593 /// IntA being the source and IntB being the dest, thus this defines a value
594 /// number in IntB. If the source value number (in IntA) is defined by a
595 /// commutable instruction and its other operand is coalesced to the copy dest
596 /// register, see if we can transform the copy into a noop by commuting the
597 /// definition. For example,
599 /// A3 = op A2 B0<kill>
601 /// B1 = A3 <- this copy
603 /// = op A3 <- more uses
607 /// B2 = op B0 A2<kill>
609 /// B1 = B2 <- now an identify copy
611 /// = op B2 <- more uses
613 /// This returns true if an interval was modified.
615 bool RegisterCoalescer::RemoveCopyByCommutingDef(const CoalescerPair &CP,
616 MachineInstr *CopyMI) {
617 // FIXME: For now, only eliminate the copy by commuting its def when the
618 // source register is a virtual register. We want to guard against cases
619 // where the copy is a back edge copy and commuting the def lengthen the
620 // live interval of the source register to the entire loop.
621 if (CP.isPhys() && CP.isFlipped())
624 // Bail if there is no dst interval.
625 if (!LIS->hasInterval(CP.getDstReg()))
628 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
631 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
633 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
635 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
636 // the example above.
637 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
638 if (!BValNo || !BValNo->isDefByCopy())
641 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
643 // AValNo is the value number in A that defines the copy, A3 in the example.
644 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
645 assert(AValNo && "COPY source not live");
647 // If other defs can reach uses of this def, then it's not safe to perform
649 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
651 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
654 if (!DefMI->isCommutable())
656 // If DefMI is a two-address instruction then commuting it will change the
657 // destination register.
658 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
659 assert(DefIdx != -1);
661 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
663 unsigned Op1, Op2, NewDstIdx;
664 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
668 else if (Op2 == UseOpIdx)
673 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
674 unsigned NewReg = NewDstMO.getReg();
675 if (NewReg != IntB.reg || !NewDstMO.isKill())
678 // Make sure there are no other definitions of IntB that would reach the
679 // uses which the new definition can reach.
680 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
683 // Abort if the aliases of IntB.reg have values that are not simply the
684 // clobbers from the superreg.
685 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
686 for (const unsigned *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
687 if (LIS->hasInterval(*AS) &&
688 HasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
691 // If some of the uses of IntA.reg is already coalesced away, return false.
692 // It's not possible to determine whether it's safe to perform the coalescing.
693 for (MachineRegisterInfo::use_nodbg_iterator UI =
694 MRI->use_nodbg_begin(IntA.reg),
695 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
696 MachineInstr *UseMI = &*UI;
697 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
698 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
699 if (ULR == IntA.end())
701 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
705 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
708 // At this point we have decided that it is legal to do this
709 // transformation. Start by commuting the instruction.
710 MachineBasicBlock *MBB = DefMI->getParent();
711 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
714 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
715 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
716 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
718 if (NewMI != DefMI) {
719 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
720 MachineBasicBlock::iterator Pos = DefMI;
721 MBB->insert(Pos, NewMI);
724 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
725 NewMI->getOperand(OpIdx).setIsKill();
727 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
736 // Update uses of IntA of the specific Val# with IntB.
737 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
738 UE = MRI->use_end(); UI != UE;) {
739 MachineOperand &UseMO = UI.getOperand();
740 MachineInstr *UseMI = &*UI;
742 if (JoinedCopies.count(UseMI))
744 if (UseMI->isDebugValue()) {
745 // FIXME These don't have an instruction index. Not clear we have enough
746 // info to decide whether to do this replacement or not. For now do it.
747 UseMO.setReg(NewReg);
750 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
751 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
752 if (ULR == IntA.end() || ULR->valno != AValNo)
754 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
755 UseMO.substPhysReg(NewReg, *TRI);
757 UseMO.setReg(NewReg);
760 if (!UseMI->isCopy())
762 if (UseMI->getOperand(0).getReg() != IntB.reg ||
763 UseMI->getOperand(0).getSubReg())
766 // This copy will become a noop. If it's defining a new val#, merge it into
768 SlotIndex DefIdx = UseIdx.getRegSlot();
769 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
772 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
773 assert(DVNI->def == DefIdx);
774 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
778 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
780 VNInfo *ValNo = BValNo;
781 ValNo->def = AValNo->def;
783 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
785 if (AI->valno != AValNo) continue;
786 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
788 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
790 IntA.removeValNo(AValNo);
791 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
796 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
797 /// computation, replace the copy by rematerialize the definition.
798 bool RegisterCoalescer::ReMaterializeTrivialDef(LiveInterval &SrcInt,
801 MachineInstr *CopyMI) {
802 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
803 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
804 assert(SrcLR != SrcInt.end() && "Live range not found!");
805 VNInfo *ValNo = SrcLR->valno;
806 if (ValNo->isPHIDef() || ValNo->isUnused())
808 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
811 assert(DefMI && "Defining instruction disappeared");
812 if (!DefMI->isAsCheapAsAMove())
814 if (!TII->isTriviallyReMaterializable(DefMI, AA))
816 bool SawStore = false;
817 if (!DefMI->isSafeToMove(TII, AA, SawStore))
819 const MCInstrDesc &MCID = DefMI->getDesc();
820 if (MCID.getNumDefs() != 1)
822 if (!DefMI->isImplicitDef()) {
823 // Make sure the copy destination register class fits the instruction
824 // definition register class. The mismatch can happen as a result of earlier
825 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
826 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI);
827 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
828 if (MRI->getRegClass(DstReg) != RC)
830 } else if (!RC->contains(DstReg))
834 RemoveCopyFlag(DstReg, CopyMI);
836 MachineBasicBlock *MBB = CopyMI->getParent();
837 MachineBasicBlock::iterator MII =
838 llvm::next(MachineBasicBlock::iterator(CopyMI));
839 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
840 MachineInstr *NewMI = prior(MII);
842 // CopyMI may have implicit operands, transfer them over to the newly
843 // rematerialized instruction. And update implicit def interval valnos.
844 for (unsigned i = CopyMI->getDesc().getNumOperands(),
845 e = CopyMI->getNumOperands(); i != e; ++i) {
846 MachineOperand &MO = CopyMI->getOperand(i);
847 if (MO.isReg() && MO.isImplicit())
848 NewMI->addOperand(MO);
850 RemoveCopyFlag(MO.getReg(), CopyMI);
853 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
854 CopyMI->eraseFromParent();
855 ReMatCopies.insert(CopyMI);
856 ReMatDefs.insert(DefMI);
857 DEBUG(dbgs() << "Remat: " << *NewMI);
860 // The source interval can become smaller because we removed a use.
862 LIS->shrinkToUses(&SrcInt);
867 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
868 /// values, it only removes local variables. When we have a copy like:
870 /// %vreg1 = COPY %vreg2<undef>
872 /// We delete the copy and remove the corresponding value number from %vreg1.
873 /// Any uses of that value number are marked as <undef>.
874 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
875 const CoalescerPair &CP) {
876 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
877 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
878 if (SrcInt->liveAt(Idx))
880 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
881 if (DstInt->liveAt(Idx))
884 // No intervals are live-in to CopyMI - it is undef.
889 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
890 assert(DeadVNI && "No value defined in DstInt");
891 DstInt->removeValNo(DeadVNI);
893 // Find new undef uses.
894 for (MachineRegisterInfo::reg_nodbg_iterator
895 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
897 MachineOperand &MO = I.getOperand();
898 if (MO.isDef() || MO.isUndef())
900 MachineInstr *MI = MO.getParent();
901 SlotIndex Idx = LIS->getInstructionIndex(MI);
902 if (DstInt->liveAt(Idx))
905 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
910 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
911 /// update the subregister number if it is not zero. If DstReg is a
912 /// physical register and the existing subregister number of the def / use
913 /// being updated is not zero, make sure to set it to the correct physical
916 RegisterCoalescer::UpdateRegDefsUses(const CoalescerPair &CP) {
917 bool DstIsPhys = CP.isPhys();
918 unsigned SrcReg = CP.getSrcReg();
919 unsigned DstReg = CP.getDstReg();
920 unsigned SubIdx = CP.getSubIdx();
922 // Update LiveDebugVariables.
923 LDV->renameRegister(SrcReg, DstReg, SubIdx);
925 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
926 MachineInstr *UseMI = I.skipInstruction();) {
927 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
930 if (UseMI->isFullCopy() &&
931 UseMI->getOperand(1).getReg() == SrcReg &&
932 UseMI->getOperand(0).getReg() != SrcReg &&
933 UseMI->getOperand(0).getReg() != DstReg &&
934 !JoinedCopies.count(UseMI) &&
935 ReMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
936 UseMI->getOperand(0).getReg(), UseMI))
940 SmallVector<unsigned,8> Ops;
942 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
943 bool Kills = false, Deads = false;
945 // Replace SrcReg with DstReg in all UseMI operands.
946 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
947 MachineOperand &MO = UseMI->getOperand(Ops[i]);
948 Kills |= MO.isKill();
949 Deads |= MO.isDead();
951 // Make sure we don't create read-modify-write defs accidentally. We
952 // assume here that a SrcReg def cannot be joined into a live DstReg. If
953 // RegisterCoalescer starts tracking partially live registers, we will
954 // need to check the actual LiveInterval to determine if DstReg is live
956 if (SubIdx && !Reads)
960 MO.substPhysReg(DstReg, *TRI);
962 MO.substVirtReg(DstReg, SubIdx, *TRI);
965 // This instruction is a copy that will be removed.
966 if (JoinedCopies.count(UseMI))
970 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
971 // read-modify-write of DstReg.
973 UseMI->addRegisterDead(DstReg, TRI);
974 else if (!Reads && Writes)
975 UseMI->addRegisterDefined(DstReg, TRI);
977 // Kill flags apply to the whole physical register.
978 if (DstIsPhys && Kills)
979 UseMI->addRegisterKilled(DstReg, TRI);
983 dbgs() << "\t\tupdated: ";
984 if (!UseMI->isDebugValue())
985 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
991 /// removeIntervalIfEmpty - Check if the live interval of a physical register
992 /// is empty, if so remove it and also remove the empty intervals of its
993 /// sub-registers. Return true if live interval is removed.
994 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
995 const TargetRegisterInfo *TRI) {
997 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
998 for (const unsigned* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
999 if (!LIS->hasInterval(*SR))
1001 LiveInterval &sli = LIS->getInterval(*SR);
1003 LIS->removeInterval(*SR);
1005 LIS->removeInterval(li.reg);
1011 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
1012 /// the val# it defines. If the live interval becomes empty, remove it as well.
1013 bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li,
1014 MachineInstr *DefMI) {
1015 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
1016 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
1017 if (DefIdx != MLR->valno->def)
1019 li.removeValNo(MLR->valno);
1020 return removeIntervalIfEmpty(li, LIS, TRI);
1023 void RegisterCoalescer::RemoveCopyFlag(unsigned DstReg,
1024 const MachineInstr *CopyMI) {
1025 SlotIndex DefIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
1026 if (LIS->hasInterval(DstReg)) {
1027 LiveInterval &LI = LIS->getInterval(DstReg);
1028 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
1029 if (LR->valno->def == DefIdx)
1030 LR->valno->setCopy(0);
1032 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
1034 for (const unsigned* AS = TRI->getAliasSet(DstReg); *AS; ++AS) {
1035 if (!LIS->hasInterval(*AS))
1037 LiveInterval &LI = LIS->getInterval(*AS);
1038 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
1039 if (LR->valno->def == DefIdx)
1040 LR->valno->setCopy(0);
1044 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
1045 /// We need to be careful about coalescing a source physical register with a
1046 /// virtual register. Once the coalescing is done, it cannot be broken and these
1047 /// are not spillable! If the destination interval uses are far away, think
1048 /// twice about coalescing them!
1049 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1050 bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1051 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1053 /// Always join simple intervals that are defined by a single copy from a
1054 /// reserved register. This doesn't increase register pressure, so it is
1055 /// always beneficial.
1056 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1059 if (!EnablePhysicalJoin) {
1060 DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1064 // Only coalesce to allocatable physreg, we don't want to risk modifying
1065 // reserved registers.
1067 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1068 return false; // Not coalescable.
1071 // Don't join with physregs that have a ridiculous number of live
1072 // ranges. The data structure performance is really bad when that
1074 if (LIS->hasInterval(CP.getDstReg()) &&
1075 LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1078 << "\tPhysical register live interval too complicated, abort!\n");
1082 // FIXME: Why are we skipping this test for partial copies?
1083 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1084 if (!CP.isPartial()) {
1085 const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1086 unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1087 unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1088 if (Length > Threshold) {
1090 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1097 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1098 /// two virtual registers from different register classes.
1100 RegisterCoalescer::isWinToJoinCrossClass(unsigned SrcReg,
1102 const TargetRegisterClass *SrcRC,
1103 const TargetRegisterClass *DstRC,
1104 const TargetRegisterClass *NewRC) {
1105 unsigned NewRCCount = RegClassInfo.getNumAllocatableRegs(NewRC);
1106 // This heuristics is good enough in practice, but it's obviously not *right*.
1107 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
1108 // out all but the most restrictive register classes.
1109 if (NewRCCount > 4 ||
1110 // Early exit if the function is fairly small, coalesce aggressively if
1111 // that's the case. For really special register classes with 3 or
1112 // fewer registers, be a bit more careful.
1113 (LIS->getFuncInstructionCount() / NewRCCount) < 8)
1115 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1116 LiveInterval &DstInt = LIS->getInterval(DstReg);
1117 unsigned SrcSize = LIS->getApproximateInstructionCount(SrcInt);
1118 unsigned DstSize = LIS->getApproximateInstructionCount(DstInt);
1120 // Coalesce aggressively if the intervals are small compared to the number of
1121 // registers in the new class. The number 4 is fairly arbitrary, chosen to be
1122 // less aggressive than the 8 used for the whole function size.
1123 const unsigned ThresSize = 4 * NewRCCount;
1124 if (SrcSize <= ThresSize && DstSize <= ThresSize)
1127 // Estimate *register use density*. If it doubles or more, abort.
1128 unsigned SrcUses = std::distance(MRI->use_nodbg_begin(SrcReg),
1129 MRI->use_nodbg_end());
1130 unsigned DstUses = std::distance(MRI->use_nodbg_begin(DstReg),
1131 MRI->use_nodbg_end());
1132 unsigned NewUses = SrcUses + DstUses;
1133 unsigned NewSize = SrcSize + DstSize;
1134 if (SrcRC != NewRC && SrcSize > ThresSize) {
1135 unsigned SrcRCCount = RegClassInfo.getNumAllocatableRegs(SrcRC);
1136 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1139 if (DstRC != NewRC && DstSize > ThresSize) {
1140 unsigned DstRCCount = RegClassInfo.getNumAllocatableRegs(DstRC);
1141 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1148 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1149 /// which are the src/dst of the copy instruction CopyMI. This returns true
1150 /// if the copy was successfully coalesced away. If it is not currently
1151 /// possible to coalesce this interval, but it may be possible if other
1152 /// things get coalesced, then it returns true by reference in 'Again'.
1153 bool RegisterCoalescer::JoinCopy(MachineInstr *CopyMI, bool &Again) {
1156 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1157 return false; // Already done.
1159 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1161 CoalescerPair CP(*TII, *TRI);
1162 if (!CP.setRegisters(CopyMI)) {
1163 DEBUG(dbgs() << "\tNot coalescable.\n");
1167 // If they are already joined we continue.
1168 if (CP.getSrcReg() == CP.getDstReg()) {
1169 markAsJoined(CopyMI);
1170 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1171 return false; // Not coalescable.
1174 // Eliminate undefs.
1175 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1176 markAsJoined(CopyMI);
1177 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1178 return false; // Not coalescable.
1181 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1182 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1185 // Enforce policies.
1187 if (!shouldJoinPhys(CP)) {
1188 // Before giving up coalescing, if definition of source is defined by
1189 // trivial computation, try rematerializing it.
1190 if (!CP.isFlipped() &&
1191 ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1192 CP.getDstReg(), CopyMI))
1197 // Avoid constraining virtual register regclass too much.
1198 if (CP.isCrossClass()) {
1199 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1200 if (DisableCrossClassJoin) {
1201 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1204 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1205 MRI->getRegClass(CP.getSrcReg()),
1206 MRI->getRegClass(CP.getDstReg()),
1208 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
1209 Again = true; // May be possible to coalesce later.
1214 // When possible, let DstReg be the larger interval.
1215 if (!CP.getSubIdx() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1216 LIS->getInterval(CP.getDstReg()).ranges.size())
1220 // Okay, attempt to join these two intervals. On failure, this returns false.
1221 // Otherwise, if one of the intervals being joined is a physreg, this method
1222 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1223 // been modified, so we can use this information below to update aliases.
1224 if (!JoinIntervals(CP)) {
1225 // Coalescing failed.
1227 // If definition of source is defined by trivial computation, try
1228 // rematerializing it.
1229 if (!CP.isFlipped() &&
1230 ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1231 CP.getDstReg(), CopyMI))
1234 // If we can eliminate the copy without merging the live ranges, do so now.
1235 if (!CP.isPartial()) {
1236 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1237 RemoveCopyByCommutingDef(CP, CopyMI)) {
1238 markAsJoined(CopyMI);
1239 DEBUG(dbgs() << "\tTrivial!\n");
1244 // Otherwise, we are unable to join the intervals.
1245 DEBUG(dbgs() << "\tInterference!\n");
1246 Again = true; // May be possible to coalesce later.
1250 // Coalescing to a virtual register that is of a sub-register class of the
1251 // other. Make sure the resulting register is set to the right register class.
1252 if (CP.isCrossClass()) {
1254 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1257 // Remember to delete the copy instruction.
1258 markAsJoined(CopyMI);
1260 UpdateRegDefsUses(CP);
1262 // If we have extended the live range of a physical register, make sure we
1263 // update live-in lists as well.
1265 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1266 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1267 // ranges for this, and they are preserved.
1268 LiveInterval &SrcInt = LIS->getInterval(CP.getSrcReg());
1269 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1271 LIS->findLiveInMBBs(I->start, I->end, BlockSeq);
1272 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1273 MachineBasicBlock &block = *BlockSeq[idx];
1274 if (!block.isLiveIn(CP.getDstReg()))
1275 block.addLiveIn(CP.getDstReg());
1281 // SrcReg is guaranteed to be the register whose live interval that is
1283 LIS->removeInterval(CP.getSrcReg());
1285 // Update regalloc hint.
1286 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1289 LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1290 dbgs() << "\tJoined. Result = ";
1291 DstInt.print(dbgs(), TRI);
1299 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1300 /// compute what the resultant value numbers for each value in the input two
1301 /// ranges will be. This is complicated by copies between the two which can
1302 /// and will commonly cause multiple value numbers to be merged into one.
1304 /// VN is the value number that we're trying to resolve. InstDefiningValue
1305 /// keeps track of the new InstDefiningValue assignment for the result
1306 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1307 /// whether a value in this or other is a copy from the opposite set.
1308 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1309 /// already been assigned.
1311 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1312 /// contains the value number the copy is from.
1314 static unsigned ComputeUltimateVN(VNInfo *VNI,
1315 SmallVector<VNInfo*, 16> &NewVNInfo,
1316 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1317 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1318 SmallVector<int, 16> &ThisValNoAssignments,
1319 SmallVector<int, 16> &OtherValNoAssignments) {
1320 unsigned VN = VNI->id;
1322 // If the VN has already been computed, just return it.
1323 if (ThisValNoAssignments[VN] >= 0)
1324 return ThisValNoAssignments[VN];
1325 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1327 // If this val is not a copy from the other val, then it must be a new value
1328 // number in the destination.
1329 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1330 if (I == ThisFromOther.end()) {
1331 NewVNInfo.push_back(VNI);
1332 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1334 VNInfo *OtherValNo = I->second;
1336 // Otherwise, this *is* a copy from the RHS. If the other side has already
1337 // been computed, return it.
1338 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1339 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1341 // Mark this value number as currently being computed, then ask what the
1342 // ultimate value # of the other value is.
1343 ThisValNoAssignments[VN] = -2;
1344 unsigned UltimateVN =
1345 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1346 OtherValNoAssignments, ThisValNoAssignments);
1347 return ThisValNoAssignments[VN] = UltimateVN;
1351 // Find out if we have something like
1354 // if so, we can pretend this is actually
1357 // which allows us to coalesce A and B.
1358 // VNI is the definition of B. LR is the life range of A that includes
1359 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1360 // This implies that A dominates B.
1361 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1362 const TargetRegisterInfo &tri,
1366 SmallVector<MachineInstr*, 8> &DupCopies) {
1367 // FIXME: This is very conservative. For example, we don't handle
1368 // physical registers.
1370 MachineInstr *MI = VNI->getCopy();
1372 if (!MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1375 unsigned Dst = MI->getOperand(0).getReg();
1376 unsigned Src = MI->getOperand(1).getReg();
1378 if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1379 !TargetRegisterInfo::isVirtualRegister(Dst))
1382 unsigned A = CP.getDstReg();
1383 unsigned B = CP.getSrcReg();
1389 VNInfo *Other = LR->valno;
1390 if (!Other->isDefByCopy())
1392 const MachineInstr *OtherMI = Other->getCopy();
1394 if (!OtherMI->isFullCopy())
1397 unsigned OtherDst = OtherMI->getOperand(0).getReg();
1398 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1400 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1401 !TargetRegisterInfo::isVirtualRegister(OtherDst))
1404 assert(OtherDst == B);
1406 if (Src != OtherSrc)
1409 // If the copies use two different value numbers of X, we cannot merge
1411 LiveInterval &SrcInt = li.getInterval(Src);
1412 // getVNInfoBefore returns NULL for undef copies. In this case, the
1413 // optimization is still safe.
1414 if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1417 DupCopies.push_back(MI);
1422 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1424 bool RegisterCoalescer::JoinIntervals(CoalescerPair &CP) {
1425 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1426 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1428 // If a live interval is a physical register, check for interference with any
1429 // aliases. The interference check implemented here is a bit more conservative
1430 // than the full interfeence check below. We allow overlapping live ranges
1431 // only when one is a copy of the other.
1433 // Optimization for reserved registers like ESP.
1434 // We can only merge with a reserved physreg if RHS has a single value that
1435 // is a copy of CP.DstReg(). The live range of the reserved register will
1436 // look like a set of dead defs - we don't properly track the live range of
1437 // reserved registers.
1438 if (RegClassInfo.isReserved(CP.getDstReg())) {
1439 assert(CP.isFlipped() && RHS.containsOneValue() &&
1440 "Invalid join with reserved register");
1441 // Deny any overlapping intervals. This depends on all the reserved
1442 // register live ranges to look like dead defs.
1443 for (const unsigned *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1444 if (!LIS->hasInterval(*AS))
1446 if (RHS.overlaps(LIS->getInterval(*AS))) {
1447 DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1451 // Skip any value computations, we are not adding new values to the
1452 // reserved register. Also skip merging the live ranges, the reserved
1453 // register live range doesn't need to be accurate as long as all the
1458 for (const unsigned *AS = TRI->getAliasSet(CP.getDstReg()); *AS; ++AS){
1459 if (!LIS->hasInterval(*AS))
1461 const LiveInterval &LHS = LIS->getInterval(*AS);
1462 LiveInterval::const_iterator LI = LHS.begin();
1463 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1465 LI = std::lower_bound(LI, LHS.end(), RI->start);
1466 // Does LHS have an overlapping live range starting before RI?
1467 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1468 (RI->start != RI->valno->def ||
1469 !CP.isCoalescable(LIS->getInstructionFromIndex(RI->start)))) {
1471 dbgs() << "\t\tInterference from alias: ";
1472 LHS.print(dbgs(), TRI);
1473 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1478 // Check that LHS ranges beginning in this range are copies.
1479 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1480 if (LI->start != LI->valno->def ||
1481 !CP.isCoalescable(LIS->getInstructionFromIndex(LI->start))) {
1483 dbgs() << "\t\tInterference from alias: ";
1484 LHS.print(dbgs(), TRI);
1485 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1494 // Compute the final value assignment, assuming that the live ranges can be
1496 SmallVector<int, 16> LHSValNoAssignments;
1497 SmallVector<int, 16> RHSValNoAssignments;
1498 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1499 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1500 SmallVector<VNInfo*, 16> NewVNInfo;
1502 SmallVector<MachineInstr*, 8> DupCopies;
1504 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1505 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1507 // Loop over the value numbers of the LHS, seeing if any are defined from
1509 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1512 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1515 // Never join with a register that has EarlyClobber redefs.
1516 if (VNI->hasRedefByEC())
1519 // Figure out the value # from the RHS.
1520 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1521 // The copy could be to an aliased physreg.
1524 // DstReg is known to be a register in the LHS interval. If the src is
1525 // from the RHS interval, we can use its value #.
1526 MachineInstr *MI = VNI->getCopy();
1527 if (!CP.isCoalescable(MI) &&
1528 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1531 LHSValsDefinedFromRHS[VNI] = lr->valno;
1534 // Loop over the value numbers of the RHS, seeing if any are defined from
1536 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1539 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1542 // Never join with a register that has EarlyClobber redefs.
1543 if (VNI->hasRedefByEC())
1546 // Figure out the value # from the LHS.
1547 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1548 // The copy could be to an aliased physreg.
1551 // DstReg is known to be a register in the RHS interval. If the src is
1552 // from the LHS interval, we can use its value #.
1553 MachineInstr *MI = VNI->getCopy();
1554 if (!CP.isCoalescable(MI) &&
1555 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1558 RHSValsDefinedFromLHS[VNI] = lr->valno;
1561 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1562 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1563 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1565 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1568 unsigned VN = VNI->id;
1569 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1571 ComputeUltimateVN(VNI, NewVNInfo,
1572 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1573 LHSValNoAssignments, RHSValNoAssignments);
1575 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1578 unsigned VN = VNI->id;
1579 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1581 // If this value number isn't a copy from the LHS, it's a new number.
1582 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1583 NewVNInfo.push_back(VNI);
1584 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1588 ComputeUltimateVN(VNI, NewVNInfo,
1589 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1590 RHSValNoAssignments, LHSValNoAssignments);
1593 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1594 // interval lists to see if these intervals are coalescable.
1595 LiveInterval::const_iterator I = LHS.begin();
1596 LiveInterval::const_iterator IE = LHS.end();
1597 LiveInterval::const_iterator J = RHS.begin();
1598 LiveInterval::const_iterator JE = RHS.end();
1600 // Skip ahead until the first place of potential sharing.
1601 if (I != IE && J != JE) {
1602 if (I->start < J->start) {
1603 I = std::upper_bound(I, IE, J->start);
1604 if (I != LHS.begin()) --I;
1605 } else if (J->start < I->start) {
1606 J = std::upper_bound(J, JE, I->start);
1607 if (J != RHS.begin()) --J;
1611 while (I != IE && J != JE) {
1612 // Determine if these two live ranges overlap.
1614 if (I->start < J->start) {
1615 Overlaps = I->end > J->start;
1617 Overlaps = J->end > I->start;
1620 // If so, check value # info to determine if they are really different.
1622 // If the live range overlap will map to the same value number in the
1623 // result liverange, we can still coalesce them. If not, we can't.
1624 if (LHSValNoAssignments[I->valno->id] !=
1625 RHSValNoAssignments[J->valno->id])
1627 // If it's re-defined by an early clobber somewhere in the live range,
1628 // then conservatively abort coalescing.
1629 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1633 if (I->end < J->end)
1639 // Update kill info. Some live ranges are extended due to copy coalescing.
1640 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1641 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1642 VNInfo *VNI = I->first;
1643 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1644 if (VNI->hasPHIKill())
1645 NewVNInfo[LHSValID]->setHasPHIKill(true);
1648 // Update kill info. Some live ranges are extended due to copy coalescing.
1649 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1650 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1651 VNInfo *VNI = I->first;
1652 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1653 if (VNI->hasPHIKill())
1654 NewVNInfo[RHSValID]->setHasPHIKill(true);
1657 if (LHSValNoAssignments.empty())
1658 LHSValNoAssignments.push_back(-1);
1659 if (RHSValNoAssignments.empty())
1660 RHSValNoAssignments.push_back(-1);
1662 SmallVector<unsigned, 8> SourceRegisters;
1663 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1664 E = DupCopies.end(); I != E; ++I) {
1665 MachineInstr *MI = *I;
1667 // We have pretended that the assignment to B in
1670 // was actually a copy from A. Now that we decided to coalesce A and B,
1671 // transform the code into
1674 // and mark the X as coalesced to keep the illusion.
1675 unsigned Src = MI->getOperand(1).getReg();
1676 SourceRegisters.push_back(Src);
1677 MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1682 // If B = X was the last use of X in a liverange, we have to shrink it now
1683 // that B = X is gone.
1684 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1685 E = SourceRegisters.end(); I != E; ++I) {
1686 LIS->shrinkToUses(&LIS->getInterval(*I));
1689 // If we get here, we know that we can coalesce the live ranges. Ask the
1690 // intervals to coalesce themselves now.
1691 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1697 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1698 // depth of the basic block (the unsigned), and then on the MBB number.
1699 struct DepthMBBCompare {
1700 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1701 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1702 // Deeper loops first
1703 if (LHS.first != RHS.first)
1704 return LHS.first > RHS.first;
1706 // Prefer blocks that are more connected in the CFG. This takes care of
1707 // the most difficult copies first while intervals are short.
1708 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1709 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1713 // As a last resort, sort by block number.
1714 return LHS.second->getNumber() < RHS.second->getNumber();
1719 void RegisterCoalescer::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1720 std::vector<MachineInstr*> &TryAgain) {
1721 DEBUG(dbgs() << MBB->getName() << ":\n");
1723 SmallVector<MachineInstr*, 8> VirtCopies;
1724 SmallVector<MachineInstr*, 8> PhysCopies;
1725 SmallVector<MachineInstr*, 8> ImpDefCopies;
1726 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1728 MachineInstr *Inst = MII++;
1730 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1731 unsigned SrcReg, DstReg;
1732 if (Inst->isCopy()) {
1733 DstReg = Inst->getOperand(0).getReg();
1734 SrcReg = Inst->getOperand(1).getReg();
1735 } else if (Inst->isSubregToReg()) {
1736 DstReg = Inst->getOperand(0).getReg();
1737 SrcReg = Inst->getOperand(2).getReg();
1741 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1742 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1743 if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1744 ImpDefCopies.push_back(Inst);
1745 else if (SrcIsPhys || DstIsPhys)
1746 PhysCopies.push_back(Inst);
1748 VirtCopies.push_back(Inst);
1751 // Try coalescing implicit copies and insert_subreg <undef> first,
1752 // followed by copies to / from physical registers, then finally copies
1753 // from virtual registers to virtual registers.
1754 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1755 MachineInstr *TheCopy = ImpDefCopies[i];
1757 if (!JoinCopy(TheCopy, Again))
1759 TryAgain.push_back(TheCopy);
1761 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1762 MachineInstr *TheCopy = PhysCopies[i];
1764 if (!JoinCopy(TheCopy, Again))
1766 TryAgain.push_back(TheCopy);
1768 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1769 MachineInstr *TheCopy = VirtCopies[i];
1771 if (!JoinCopy(TheCopy, Again))
1773 TryAgain.push_back(TheCopy);
1777 void RegisterCoalescer::joinIntervals() {
1778 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1780 std::vector<MachineInstr*> TryAgainList;
1781 if (Loops->empty()) {
1782 // If there are no loops in the function, join intervals in function order.
1783 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1785 CopyCoalesceInMBB(I, TryAgainList);
1787 // Otherwise, join intervals in inner loops before other intervals.
1788 // Unfortunately we can't just iterate over loop hierarchy here because
1789 // there may be more MBB's than BB's. Collect MBB's for sorting.
1791 // Join intervals in the function prolog first. We want to join physical
1792 // registers with virtual registers before the intervals got too long.
1793 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1794 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1795 MachineBasicBlock *MBB = I;
1796 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1799 // Sort by loop depth.
1800 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1802 // Finally, join intervals in loop nest order.
1803 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1804 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1807 // Joining intervals can allow other intervals to be joined. Iteratively join
1808 // until we make no progress.
1809 bool ProgressMade = true;
1810 while (ProgressMade) {
1811 ProgressMade = false;
1813 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1814 MachineInstr *&TheCopy = TryAgainList[i];
1819 bool Success = JoinCopy(TheCopy, Again);
1820 if (Success || !Again) {
1821 TheCopy= 0; // Mark this one as done.
1822 ProgressMade = true;
1828 void RegisterCoalescer::releaseMemory() {
1829 JoinedCopies.clear();
1830 ReMatCopies.clear();
1834 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1836 MRI = &fn.getRegInfo();
1837 TM = &fn.getTarget();
1838 TRI = TM->getRegisterInfo();
1839 TII = TM->getInstrInfo();
1840 LIS = &getAnalysis<LiveIntervals>();
1841 LDV = &getAnalysis<LiveDebugVariables>();
1842 AA = &getAnalysis<AliasAnalysis>();
1843 Loops = &getAnalysis<MachineLoopInfo>();
1845 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1846 << "********** Function: "
1847 << ((Value*)MF->getFunction())->getName() << '\n');
1849 if (VerifyCoalescing)
1850 MF->verify(this, "Before register coalescing");
1852 RegClassInfo.runOnMachineFunction(fn);
1854 // Join (coalesce) intervals if requested.
1855 if (EnableJoining) {
1858 dbgs() << "********** INTERVALS POST JOINING **********\n";
1859 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1861 I->second->print(dbgs(), TRI);
1867 // Perform a final pass over the instructions and compute spill weights
1868 // and remove identity moves.
1869 SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1870 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1871 mbbi != mbbe; ++mbbi) {
1872 MachineBasicBlock* mbb = mbbi;
1873 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1875 MachineInstr *MI = mii;
1876 if (JoinedCopies.count(MI)) {
1877 // Delete all coalesced copies.
1878 bool DoDelete = true;
1879 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1880 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1881 unsigned DstReg = MI->getOperand(0).getReg();
1883 // Collect candidates for register class inflation.
1884 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1885 RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1886 InflateRegs.push_back(SrcReg);
1887 if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1888 RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1889 InflateRegs.push_back(DstReg);
1891 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1892 MI->getNumOperands() > 2)
1893 // Do not delete extract_subreg, insert_subreg of physical
1894 // registers unless the definition is dead. e.g.
1895 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1896 // or else the scavenger may complain. LowerSubregs will
1897 // delete them later.
1900 if (MI->allDefsAreDead()) {
1901 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1902 LIS->hasInterval(SrcReg))
1903 LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1907 // We need the instruction to adjust liveness, so make it a KILL.
1908 if (MI->isSubregToReg()) {
1909 MI->RemoveOperand(3);
1910 MI->RemoveOperand(1);
1912 MI->setDesc(TII->get(TargetOpcode::KILL));
1913 mii = llvm::next(mii);
1915 LIS->RemoveMachineInstrFromMaps(MI);
1916 mii = mbbi->erase(mii);
1922 // Now check if this is a remat'ed def instruction which is now dead.
1923 if (ReMatDefs.count(MI)) {
1925 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1926 const MachineOperand &MO = MI->getOperand(i);
1929 unsigned Reg = MO.getReg();
1932 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1933 DeadDefs.push_back(Reg);
1934 // Remat may also enable register class inflation.
1935 if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1936 InflateRegs.push_back(Reg);
1940 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1941 !MRI->use_nodbg_empty(Reg)) {
1947 while (!DeadDefs.empty()) {
1948 unsigned DeadDef = DeadDefs.back();
1949 DeadDefs.pop_back();
1950 RemoveDeadDef(LIS->getInterval(DeadDef), MI);
1952 LIS->RemoveMachineInstrFromMaps(mii);
1953 mii = mbbi->erase(mii);
1961 // Check for now unnecessary kill flags.
1962 if (LIS->isNotInMIMap(MI)) continue;
1963 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1964 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1965 MachineOperand &MO = MI->getOperand(i);
1966 if (!MO.isReg() || !MO.isKill()) continue;
1967 unsigned reg = MO.getReg();
1968 if (!reg || !LIS->hasInterval(reg)) continue;
1969 if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1970 MO.setIsKill(false);
1973 // When leaving a kill flag on a physreg, check if any subregs should
1975 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1977 for (const unsigned *SR = TRI->getSubRegisters(reg);
1978 unsigned S = *SR; ++SR)
1979 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1980 MI->addRegisterDefined(S, TRI);
1985 // After deleting a lot of copies, register classes may be less constrained.
1986 // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1988 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1989 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1991 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1992 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1993 unsigned Reg = InflateRegs[i];
1994 if (MRI->reg_nodbg_empty(Reg))
1996 if (MRI->recomputeRegClass(Reg, *TM)) {
1997 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1998 << MRI->getRegClass(Reg)->getName() << '\n');
2005 if (VerifyCoalescing)
2006 MF->verify(this, "After register coalescing");
2010 /// print - Implement the dump method.
2011 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {