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 EnablePhysicalJoin("join-physregs",
67 cl::desc("Join physical register copies"),
68 cl::init(false), cl::Hidden);
71 VerifyCoalescing("verify-coalescing",
72 cl::desc("Verify machine instrs before and after register coalescing"),
76 class RegisterCoalescer : public MachineFunctionPass {
78 MachineRegisterInfo* MRI;
79 const TargetMachine* TM;
80 const TargetRegisterInfo* TRI;
81 const TargetInstrInfo* TII;
83 LiveDebugVariables *LDV;
84 const MachineLoopInfo* Loops;
86 RegisterClassInfo RegClassInfo;
88 /// JoinedCopies - Keep track of copies eliminated due to coalescing.
90 SmallPtrSet<MachineInstr*, 32> JoinedCopies;
92 /// ReMatCopies - Keep track of copies eliminated due to remat.
94 SmallPtrSet<MachineInstr*, 32> ReMatCopies;
96 /// ReMatDefs - Keep track of definition instructions which have
98 SmallPtrSet<MachineInstr*, 8> ReMatDefs;
100 /// joinAllIntervals - join compatible live intervals
101 void joinAllIntervals();
103 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
104 /// copies that cannot yet be coalesced into the "TryAgain" list.
105 void copyCoalesceInMBB(MachineBasicBlock *MBB,
106 std::vector<MachineInstr*> &TryAgain);
108 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
109 /// which are the src/dst of the copy instruction CopyMI. This returns
110 /// true if the copy was successfully coalesced away. If it is not
111 /// currently possible to coalesce this interval, but it may be possible if
112 /// other things get coalesced, then it returns true by reference in
114 bool joinCopy(MachineInstr *TheCopy, bool &Again);
116 /// joinIntervals - Attempt to join these two intervals. On failure, this
117 /// returns false. The output "SrcInt" will not have been modified, so we
118 /// can use this information below to update aliases.
119 bool joinIntervals(CoalescerPair &CP);
121 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
122 /// the source value number is defined by a copy from the destination reg
123 /// see if we can merge these two destination reg valno# into a single
124 /// value number, eliminating a copy.
125 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
127 /// hasOtherReachingDefs - Return true if there are definitions of IntB
128 /// other than BValNo val# that can reach uses of AValno val# of IntA.
129 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
130 VNInfo *AValNo, VNInfo *BValNo);
132 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
133 /// If the source value number is defined by a commutable instruction and
134 /// its other operand is coalesced to the copy dest register, see if we
135 /// can transform the copy into a noop by commuting the definition.
136 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
138 /// reMaterializeTrivialDef - If the source of a copy is defined by a
139 /// trivial computation, replace the copy by rematerialize the definition.
140 /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
141 bool reMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
142 unsigned DstReg, MachineInstr *CopyMI);
144 /// shouldJoinPhys - Return true if a physreg copy should be joined.
145 bool shouldJoinPhys(CoalescerPair &CP);
147 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
148 /// update the subregister number if it is not zero. If DstReg is a
149 /// physical register and the existing subregister number of the def / use
150 /// being updated is not zero, make sure to set it to the correct physical
152 void updateRegDefsUses(const CoalescerPair &CP);
154 /// removeDeadDef - If a def of a live interval is now determined dead,
155 /// remove the val# it defines. If the live interval becomes empty, remove
157 bool removeDeadDef(LiveInterval &li, MachineInstr *DefMI);
159 /// markAsJoined - Remember that CopyMI has already been joined.
160 void markAsJoined(MachineInstr *CopyMI);
162 /// eliminateUndefCopy - Handle copies of undef values.
163 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
166 static char ID; // Class identification, replacement for typeinfo
167 RegisterCoalescer() : MachineFunctionPass(ID) {
168 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
171 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
173 virtual void releaseMemory();
175 /// runOnMachineFunction - pass entry point
176 virtual bool runOnMachineFunction(MachineFunction&);
178 /// print - Implement the dump method.
179 virtual void print(raw_ostream &O, const Module* = 0) const;
181 } /// end anonymous namespace
183 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
185 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
186 "Simple Register Coalescing", false, false)
187 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
188 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
189 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
190 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
191 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
192 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
193 "Simple Register Coalescing", false, false)
195 char RegisterCoalescer::ID = 0;
197 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
200 return tri.composeSubRegIndices(a, b);
203 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
204 unsigned &Src, unsigned &Dst,
205 unsigned &SrcSub, unsigned &DstSub) {
207 Dst = MI->getOperand(0).getReg();
208 DstSub = MI->getOperand(0).getSubReg();
209 Src = MI->getOperand(1).getReg();
210 SrcSub = MI->getOperand(1).getSubReg();
211 } else if (MI->isSubregToReg()) {
212 Dst = MI->getOperand(0).getReg();
213 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
214 MI->getOperand(3).getImm());
215 Src = MI->getOperand(2).getReg();
216 SrcSub = MI->getOperand(2).getSubReg();
222 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
223 SrcReg = DstReg = SubIdx = 0;
225 Flipped = CrossClass = false;
227 unsigned Src, Dst, SrcSub, DstSub;
228 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
230 Partial = SrcSub || DstSub;
232 // If one register is a physreg, it must be Dst.
233 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
234 if (TargetRegisterInfo::isPhysicalRegister(Dst))
237 std::swap(SrcSub, DstSub);
241 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
243 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
244 // Eliminate DstSub on a physreg.
246 Dst = TRI.getSubReg(Dst, DstSub);
247 if (!Dst) return false;
251 // Eliminate SrcSub by picking a corresponding Dst superregister.
253 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
254 if (!Dst) return false;
256 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
260 // Both registers are virtual.
261 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
262 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
264 // Both registers have subreg indices.
265 if (SrcSub && DstSub) {
266 unsigned SrcPre, DstPre;
267 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
272 // We cannot handle the case where both Src and Dst would be a
273 // sub-register. Yet.
274 if (SrcPre && DstPre) {
275 DEBUG(dbgs() << "\tCannot handle " << NewRC->getName()
276 << " with subregs " << TRI.getSubRegIndexName(SrcPre)
277 << " and " << TRI.getSubRegIndexName(DstPre) << '\n');
281 // One of these will be 0, so one register is a sub-register of the other.
286 // There can be no SrcSub.
289 std::swap(SrcRC, DstRC);
292 assert(!Flipped && "Unexpected flip");
296 // Find the new register class.
299 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
301 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
305 CrossClass = NewRC != DstRC || NewRC != SrcRC;
307 // Check our invariants
308 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
309 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
310 "Cannot have a physical SubIdx");
317 bool CoalescerPair::flip() {
318 if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg))
320 std::swap(SrcReg, DstReg);
325 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
328 unsigned Src, Dst, SrcSub, DstSub;
329 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
332 // Find the virtual register that is SrcReg.
335 std::swap(SrcSub, DstSub);
336 } else if (Src != SrcReg) {
340 // Now check that Dst matches DstReg.
341 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
342 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
344 assert(!SubIdx && "Inconsistent CoalescerPair state.");
345 // DstSub could be set for a physreg from INSERT_SUBREG.
347 Dst = TRI.getSubReg(Dst, DstSub);
350 return DstReg == Dst;
351 // This is a partial register copy. Check that the parts match.
352 return TRI.getSubReg(DstReg, SrcSub) == Dst;
354 // DstReg is virtual.
357 // Registers match, do the subregisters line up?
358 return compose(TRI, SubIdx, SrcSub) == DstSub;
362 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
363 AU.setPreservesCFG();
364 AU.addRequired<AliasAnalysis>();
365 AU.addRequired<LiveIntervals>();
366 AU.addPreserved<LiveIntervals>();
367 AU.addRequired<LiveDebugVariables>();
368 AU.addPreserved<LiveDebugVariables>();
369 AU.addPreserved<SlotIndexes>();
370 AU.addRequired<MachineLoopInfo>();
371 AU.addPreserved<MachineLoopInfo>();
372 AU.addPreservedID(MachineDominatorsID);
373 MachineFunctionPass::getAnalysisUsage(AU);
376 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
377 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
378 JoinedCopies.insert(CopyMI);
380 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
381 /// code elimination.
382 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
383 E = CopyMI->operands_end(); I != E; ++I)
388 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
389 /// being the source and IntB being the dest, thus this defines a value number
390 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
391 /// see if we can merge these two pieces of B into a single value number,
392 /// eliminating a copy. For example:
396 /// B1 = A3 <- this copy
398 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
399 /// value number to be replaced with B0 (which simplifies the B liveinterval).
401 /// This returns true if an interval was modified.
403 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
404 MachineInstr *CopyMI) {
405 // Bail if there is no dst interval - can happen when merging physical subreg
407 if (!LIS->hasInterval(CP.getDstReg()))
411 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
413 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
414 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
416 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
417 // the example above.
418 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
419 if (BLR == IntB.end()) return false;
420 VNInfo *BValNo = BLR->valno;
422 // Get the location that B is defined at. Two options: either this value has
423 // an unknown definition point or it is defined at CopyIdx. If unknown, we
425 if (BValNo->def != CopyIdx) return false;
427 // AValNo is the value number in A that defines the copy, A3 in the example.
428 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
429 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
430 // The live range might not exist after fun with physreg coalescing.
431 if (ALR == IntA.end()) return false;
432 VNInfo *AValNo = ALR->valno;
434 // If AValNo is defined as a copy from IntB, we can potentially process this.
435 // Get the instruction that defines this value number.
436 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
437 if (!CP.isCoalescable(ACopyMI))
440 // Get the LiveRange in IntB that this value number starts with.
441 LiveInterval::iterator ValLR =
442 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
443 if (ValLR == IntB.end())
446 // Make sure that the end of the live range is inside the same block as
448 MachineInstr *ValLREndInst =
449 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
450 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
453 // Okay, we now know that ValLR ends in the same block that the CopyMI
454 // live-range starts. If there are no intervening live ranges between them in
455 // IntB, we can merge them.
456 if (ValLR+1 != BLR) return false;
458 // If a live interval is a physical register, conservatively check if any
459 // of its aliases is overlapping the live interval of the virtual register.
460 // If so, do not coalesce.
461 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
462 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
463 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
465 dbgs() << "\t\tInterfere with alias ";
466 LIS->getInterval(*AS).print(dbgs(), TRI);
473 dbgs() << "Extending: ";
474 IntB.print(dbgs(), TRI);
477 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
478 // We are about to delete CopyMI, so need to remove it as the 'instruction
479 // that defines this value #'. Update the valnum with the new defining
481 BValNo->def = FillerStart;
483 // Okay, we can merge them. We need to insert a new liverange:
484 // [ValLR.end, BLR.begin) of either value number, then we merge the
485 // two value numbers.
486 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
488 // If the IntB live range is assigned to a physical register, and if that
489 // physreg has sub-registers, update their live intervals as well.
490 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
491 for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
492 if (!LIS->hasInterval(*SR))
494 LiveInterval &SRLI = LIS->getInterval(*SR);
495 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
496 SRLI.getNextValue(FillerStart,
497 LIS->getVNInfoAllocator())));
501 // Okay, merge "B1" into the same value number as "B0".
502 if (BValNo != ValLR->valno) {
503 // If B1 is killed by a PHI, then the merged live range must also be killed
504 // by the same PHI, as B0 and B1 can not overlap.
505 bool HasPHIKill = BValNo->hasPHIKill();
506 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
508 ValLR->valno->setHasPHIKill(true);
511 dbgs() << " result = ";
512 IntB.print(dbgs(), TRI);
516 // If the source instruction was killing the source register before the
517 // merge, unset the isKill marker given the live range has been extended.
518 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
520 ValLREndInst->getOperand(UIdx).setIsKill(false);
523 // Rewrite the copy. If the copy instruction was killing the destination
524 // register before the merge, find the last use and trim the live range. That
525 // will also add the isKill marker.
526 CopyMI->substituteRegister(IntA.reg, IntB.reg, CP.getSubIdx(),
528 if (ALR->end == CopyIdx)
529 LIS->shrinkToUses(&IntA);
535 /// hasOtherReachingDefs - Return true if there are definitions of IntB
536 /// other than BValNo val# that can reach uses of AValno val# of IntA.
537 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
541 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
543 if (AI->valno != AValNo) continue;
544 LiveInterval::Ranges::iterator BI =
545 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
546 if (BI != IntB.ranges.begin())
548 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
549 if (BI->valno == BValNo)
551 if (BI->start <= AI->start && BI->end > AI->start)
553 if (BI->start > AI->start && BI->start < AI->end)
560 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
561 /// IntA being the source and IntB being the dest, thus this defines a value
562 /// number in IntB. If the source value number (in IntA) is defined by a
563 /// commutable instruction and its other operand is coalesced to the copy dest
564 /// register, see if we can transform the copy into a noop by commuting the
565 /// definition. For example,
567 /// A3 = op A2 B0<kill>
569 /// B1 = A3 <- this copy
571 /// = op A3 <- more uses
575 /// B2 = op B0 A2<kill>
577 /// B1 = B2 <- now an identify copy
579 /// = op B2 <- more uses
581 /// This returns true if an interval was modified.
583 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
584 MachineInstr *CopyMI) {
585 // FIXME: For now, only eliminate the copy by commuting its def when the
586 // source register is a virtual register. We want to guard against cases
587 // where the copy is a back edge copy and commuting the def lengthen the
588 // live interval of the source register to the entire loop.
589 if (CP.isPhys() && CP.isFlipped())
592 // Bail if there is no dst interval.
593 if (!LIS->hasInterval(CP.getDstReg()))
596 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
599 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
601 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
603 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
604 // the example above.
605 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
606 if (!BValNo || BValNo->def != CopyIdx)
609 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
611 // AValNo is the value number in A that defines the copy, A3 in the example.
612 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
613 assert(AValNo && "COPY source not live");
615 // If other defs can reach uses of this def, then it's not safe to perform
617 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
619 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
622 if (!DefMI->isCommutable())
624 // If DefMI is a two-address instruction then commuting it will change the
625 // destination register.
626 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
627 assert(DefIdx != -1);
629 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
631 unsigned Op1, Op2, NewDstIdx;
632 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
636 else if (Op2 == UseOpIdx)
641 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
642 unsigned NewReg = NewDstMO.getReg();
643 if (NewReg != IntB.reg || !NewDstMO.isKill())
646 // Make sure there are no other definitions of IntB that would reach the
647 // uses which the new definition can reach.
648 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
651 // Abort if the aliases of IntB.reg have values that are not simply the
652 // clobbers from the superreg.
653 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
654 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
655 if (LIS->hasInterval(*AS) &&
656 hasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
659 // If some of the uses of IntA.reg is already coalesced away, return false.
660 // It's not possible to determine whether it's safe to perform the coalescing.
661 for (MachineRegisterInfo::use_nodbg_iterator UI =
662 MRI->use_nodbg_begin(IntA.reg),
663 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
664 MachineInstr *UseMI = &*UI;
665 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
666 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
667 if (ULR == IntA.end())
669 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
673 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
676 // At this point we have decided that it is legal to do this
677 // transformation. Start by commuting the instruction.
678 MachineBasicBlock *MBB = DefMI->getParent();
679 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
682 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
683 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
684 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
686 if (NewMI != DefMI) {
687 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
688 MachineBasicBlock::iterator Pos = DefMI;
689 MBB->insert(Pos, NewMI);
692 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
693 NewMI->getOperand(OpIdx).setIsKill();
695 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
704 // Update uses of IntA of the specific Val# with IntB.
705 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
706 UE = MRI->use_end(); UI != UE;) {
707 MachineOperand &UseMO = UI.getOperand();
708 MachineInstr *UseMI = &*UI;
710 if (JoinedCopies.count(UseMI))
712 if (UseMI->isDebugValue()) {
713 // FIXME These don't have an instruction index. Not clear we have enough
714 // info to decide whether to do this replacement or not. For now do it.
715 UseMO.setReg(NewReg);
718 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
719 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
720 if (ULR == IntA.end() || ULR->valno != AValNo)
722 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
723 UseMO.substPhysReg(NewReg, *TRI);
725 UseMO.setReg(NewReg);
728 if (!UseMI->isCopy())
730 if (UseMI->getOperand(0).getReg() != IntB.reg ||
731 UseMI->getOperand(0).getSubReg())
734 // This copy will become a noop. If it's defining a new val#, merge it into
736 SlotIndex DefIdx = UseIdx.getRegSlot();
737 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
740 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
741 assert(DVNI->def == DefIdx);
742 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
746 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
748 VNInfo *ValNo = BValNo;
749 ValNo->def = AValNo->def;
750 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
752 if (AI->valno != AValNo) continue;
753 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
755 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
757 IntA.removeValNo(AValNo);
758 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
763 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
764 /// computation, replace the copy by rematerialize the definition.
765 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
768 MachineInstr *CopyMI) {
769 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
770 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
771 assert(SrcLR != SrcInt.end() && "Live range not found!");
772 VNInfo *ValNo = SrcLR->valno;
773 if (ValNo->isPHIDef() || ValNo->isUnused())
775 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
778 assert(DefMI && "Defining instruction disappeared");
779 if (!DefMI->isAsCheapAsAMove())
781 if (!TII->isTriviallyReMaterializable(DefMI, AA))
783 bool SawStore = false;
784 if (!DefMI->isSafeToMove(TII, AA, SawStore))
786 const MCInstrDesc &MCID = DefMI->getDesc();
787 if (MCID.getNumDefs() != 1)
789 if (!DefMI->isImplicitDef()) {
790 // Make sure the copy destination register class fits the instruction
791 // definition register class. The mismatch can happen as a result of earlier
792 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
793 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
794 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
795 if (MRI->getRegClass(DstReg) != RC)
797 } else if (!RC->contains(DstReg))
801 MachineBasicBlock *MBB = CopyMI->getParent();
802 MachineBasicBlock::iterator MII =
803 llvm::next(MachineBasicBlock::iterator(CopyMI));
804 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
805 MachineInstr *NewMI = prior(MII);
807 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
808 // We need to remember these so we can add intervals once we insert
809 // NewMI into SlotIndexes.
810 SmallVector<unsigned, 4> NewMIImplDefs;
811 for (unsigned i = NewMI->getDesc().getNumOperands(),
812 e = NewMI->getNumOperands(); i != e; ++i) {
813 MachineOperand &MO = NewMI->getOperand(i);
815 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
816 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
817 NewMIImplDefs.push_back(MO.getReg());
821 // CopyMI may have implicit operands, transfer them over to the newly
822 // rematerialized instruction. And update implicit def interval valnos.
823 for (unsigned i = CopyMI->getDesc().getNumOperands(),
824 e = CopyMI->getNumOperands(); i != e; ++i) {
825 MachineOperand &MO = CopyMI->getOperand(i);
827 assert(MO.isImplicit() && "No explicit operands after implict operands.");
828 // Discard VReg implicit defs.
829 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
830 NewMI->addOperand(MO);
835 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
837 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
838 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
839 unsigned reg = NewMIImplDefs[i];
840 LiveInterval &li = LIS->getInterval(reg);
841 VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
842 LIS->getVNInfoAllocator());
843 LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
847 CopyMI->eraseFromParent();
848 ReMatCopies.insert(CopyMI);
849 ReMatDefs.insert(DefMI);
850 DEBUG(dbgs() << "Remat: " << *NewMI);
853 // The source interval can become smaller because we removed a use.
855 LIS->shrinkToUses(&SrcInt);
860 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
861 /// values, it only removes local variables. When we have a copy like:
863 /// %vreg1 = COPY %vreg2<undef>
865 /// We delete the copy and remove the corresponding value number from %vreg1.
866 /// Any uses of that value number are marked as <undef>.
867 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
868 const CoalescerPair &CP) {
869 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
870 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
871 if (SrcInt->liveAt(Idx))
873 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
874 if (DstInt->liveAt(Idx))
877 // No intervals are live-in to CopyMI - it is undef.
882 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
883 assert(DeadVNI && "No value defined in DstInt");
884 DstInt->removeValNo(DeadVNI);
886 // Find new undef uses.
887 for (MachineRegisterInfo::reg_nodbg_iterator
888 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
890 MachineOperand &MO = I.getOperand();
891 if (MO.isDef() || MO.isUndef())
893 MachineInstr *MI = MO.getParent();
894 SlotIndex Idx = LIS->getInstructionIndex(MI);
895 if (DstInt->liveAt(Idx))
898 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
903 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
904 /// update the subregister number if it is not zero. If DstReg is a
905 /// physical register and the existing subregister number of the def / use
906 /// being updated is not zero, make sure to set it to the correct physical
908 void RegisterCoalescer::updateRegDefsUses(const CoalescerPair &CP) {
909 bool DstIsPhys = CP.isPhys();
910 unsigned SrcReg = CP.getSrcReg();
911 unsigned DstReg = CP.getDstReg();
912 unsigned SubIdx = CP.getSubIdx();
914 // Update LiveDebugVariables.
915 LDV->renameRegister(SrcReg, DstReg, SubIdx);
917 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
918 MachineInstr *UseMI = I.skipInstruction();) {
919 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
922 if (UseMI->isFullCopy() &&
923 UseMI->getOperand(1).getReg() == SrcReg &&
924 UseMI->getOperand(0).getReg() != SrcReg &&
925 UseMI->getOperand(0).getReg() != DstReg &&
926 !JoinedCopies.count(UseMI) &&
927 reMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
928 UseMI->getOperand(0).getReg(), UseMI))
932 SmallVector<unsigned,8> Ops;
934 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
936 // Replace SrcReg with DstReg in all UseMI operands.
937 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
938 MachineOperand &MO = UseMI->getOperand(Ops[i]);
940 // Make sure we don't create read-modify-write defs accidentally. We
941 // assume here that a SrcReg def cannot be joined into a live DstReg. If
942 // RegisterCoalescer starts tracking partially live registers, we will
943 // need to check the actual LiveInterval to determine if DstReg is live
945 if (SubIdx && !Reads)
949 MO.substPhysReg(DstReg, *TRI);
951 MO.substVirtReg(DstReg, SubIdx, *TRI);
954 // This instruction is a copy that will be removed.
955 if (JoinedCopies.count(UseMI))
959 dbgs() << "\t\tupdated: ";
960 if (!UseMI->isDebugValue())
961 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
967 /// removeIntervalIfEmpty - Check if the live interval of a physical register
968 /// is empty, if so remove it and also remove the empty intervals of its
969 /// sub-registers. Return true if live interval is removed.
970 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
971 const TargetRegisterInfo *TRI) {
973 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
974 for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
975 if (!LIS->hasInterval(*SR))
977 LiveInterval &sli = LIS->getInterval(*SR);
979 LIS->removeInterval(*SR);
981 LIS->removeInterval(li.reg);
987 /// removeDeadDef - If a def of a live interval is now determined dead, remove
988 /// the val# it defines. If the live interval becomes empty, remove it as well.
989 bool RegisterCoalescer::removeDeadDef(LiveInterval &li, MachineInstr *DefMI) {
990 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
991 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
992 if (DefIdx != MLR->valno->def)
994 li.removeValNo(MLR->valno);
995 return removeIntervalIfEmpty(li, LIS, TRI);
998 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
999 /// We need to be careful about coalescing a source physical register with a
1000 /// virtual register. Once the coalescing is done, it cannot be broken and these
1001 /// are not spillable! If the destination interval uses are far away, think
1002 /// twice about coalescing them!
1003 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1004 bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1005 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1007 /// Always join simple intervals that are defined by a single copy from a
1008 /// reserved register. This doesn't increase register pressure, so it is
1009 /// always beneficial.
1010 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1013 if (!EnablePhysicalJoin) {
1014 DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1018 // Only coalesce to allocatable physreg, we don't want to risk modifying
1019 // reserved registers.
1021 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1022 return false; // Not coalescable.
1025 // Don't join with physregs that have a ridiculous number of live
1026 // ranges. The data structure performance is really bad when that
1028 if (LIS->hasInterval(CP.getDstReg()) &&
1029 LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1032 << "\tPhysical register live interval too complicated, abort!\n");
1036 // FIXME: Why are we skipping this test for partial copies?
1037 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1038 if (!CP.isPartial()) {
1039 const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1040 unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1041 unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1042 if (Length > Threshold) {
1044 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1052 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1053 /// which are the src/dst of the copy instruction CopyMI. This returns true
1054 /// if the copy was successfully coalesced away. If it is not currently
1055 /// possible to coalesce this interval, but it may be possible if other
1056 /// things get coalesced, then it returns true by reference in 'Again'.
1057 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1060 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1061 return false; // Already done.
1063 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1065 CoalescerPair CP(*TII, *TRI);
1066 if (!CP.setRegisters(CopyMI)) {
1067 DEBUG(dbgs() << "\tNot coalescable.\n");
1071 // If they are already joined we continue.
1072 if (CP.getSrcReg() == CP.getDstReg()) {
1073 markAsJoined(CopyMI);
1074 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1075 return false; // Not coalescable.
1078 // Eliminate undefs.
1079 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1080 markAsJoined(CopyMI);
1081 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1082 return false; // Not coalescable.
1085 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1086 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1089 // Enforce policies.
1091 if (!shouldJoinPhys(CP)) {
1092 // Before giving up coalescing, if definition of source is defined by
1093 // trivial computation, try rematerializing it.
1094 if (!CP.isFlipped() &&
1095 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1096 CP.getDstReg(), CopyMI))
1102 if (CP.isCrossClass())
1103 dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n";
1106 // When possible, let DstReg be the larger interval.
1107 if (!CP.getSubIdx() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1108 LIS->getInterval(CP.getDstReg()).ranges.size())
1112 // Okay, attempt to join these two intervals. On failure, this returns false.
1113 // Otherwise, if one of the intervals being joined is a physreg, this method
1114 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1115 // been modified, so we can use this information below to update aliases.
1116 if (!joinIntervals(CP)) {
1117 // Coalescing failed.
1119 // If definition of source is defined by trivial computation, try
1120 // rematerializing it.
1121 if (!CP.isFlipped() &&
1122 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1123 CP.getDstReg(), CopyMI))
1126 // If we can eliminate the copy without merging the live ranges, do so now.
1127 if (!CP.isPartial()) {
1128 if (adjustCopiesBackFrom(CP, CopyMI) ||
1129 removeCopyByCommutingDef(CP, CopyMI)) {
1130 markAsJoined(CopyMI);
1131 DEBUG(dbgs() << "\tTrivial!\n");
1136 // Otherwise, we are unable to join the intervals.
1137 DEBUG(dbgs() << "\tInterference!\n");
1138 Again = true; // May be possible to coalesce later.
1142 // Coalescing to a virtual register that is of a sub-register class of the
1143 // other. Make sure the resulting register is set to the right register class.
1144 if (CP.isCrossClass()) {
1146 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1149 // Remember to delete the copy instruction.
1150 markAsJoined(CopyMI);
1152 updateRegDefsUses(CP);
1154 // If we have extended the live range of a physical register, make sure we
1155 // update live-in lists as well.
1157 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1158 // joinIntervals invalidates the VNInfos in SrcInt, but we only need the
1159 // ranges for this, and they are preserved.
1160 LiveInterval &SrcInt = LIS->getInterval(CP.getSrcReg());
1161 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1163 LIS->findLiveInMBBs(I->start, I->end, BlockSeq);
1164 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1165 MachineBasicBlock &block = *BlockSeq[idx];
1166 if (!block.isLiveIn(CP.getDstReg()))
1167 block.addLiveIn(CP.getDstReg());
1173 // SrcReg is guaranteed to be the register whose live interval that is
1175 LIS->removeInterval(CP.getSrcReg());
1177 // Update regalloc hint.
1178 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1181 LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1182 dbgs() << "\tJoined. Result = ";
1183 DstInt.print(dbgs(), TRI);
1191 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1192 /// compute what the resultant value numbers for each value in the input two
1193 /// ranges will be. This is complicated by copies between the two which can
1194 /// and will commonly cause multiple value numbers to be merged into one.
1196 /// VN is the value number that we're trying to resolve. InstDefiningValue
1197 /// keeps track of the new InstDefiningValue assignment for the result
1198 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1199 /// whether a value in this or other is a copy from the opposite set.
1200 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1201 /// already been assigned.
1203 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1204 /// contains the value number the copy is from.
1206 static unsigned ComputeUltimateVN(VNInfo *VNI,
1207 SmallVector<VNInfo*, 16> &NewVNInfo,
1208 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1209 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1210 SmallVector<int, 16> &ThisValNoAssignments,
1211 SmallVector<int, 16> &OtherValNoAssignments) {
1212 unsigned VN = VNI->id;
1214 // If the VN has already been computed, just return it.
1215 if (ThisValNoAssignments[VN] >= 0)
1216 return ThisValNoAssignments[VN];
1217 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1219 // If this val is not a copy from the other val, then it must be a new value
1220 // number in the destination.
1221 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1222 if (I == ThisFromOther.end()) {
1223 NewVNInfo.push_back(VNI);
1224 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1226 VNInfo *OtherValNo = I->second;
1228 // Otherwise, this *is* a copy from the RHS. If the other side has already
1229 // been computed, return it.
1230 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1231 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1233 // Mark this value number as currently being computed, then ask what the
1234 // ultimate value # of the other value is.
1235 ThisValNoAssignments[VN] = -2;
1236 unsigned UltimateVN =
1237 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1238 OtherValNoAssignments, ThisValNoAssignments);
1239 return ThisValNoAssignments[VN] = UltimateVN;
1243 // Find out if we have something like
1246 // if so, we can pretend this is actually
1249 // which allows us to coalesce A and B.
1250 // VNI is the definition of B. LR is the life range of A that includes
1251 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1252 // This implies that A dominates B.
1253 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1254 const TargetRegisterInfo &tri,
1258 SmallVector<MachineInstr*, 8> &DupCopies) {
1259 // FIXME: This is very conservative. For example, we don't handle
1260 // physical registers.
1262 MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1264 if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1267 unsigned Dst = MI->getOperand(0).getReg();
1268 unsigned Src = MI->getOperand(1).getReg();
1270 if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1271 !TargetRegisterInfo::isVirtualRegister(Dst))
1274 unsigned A = CP.getDstReg();
1275 unsigned B = CP.getSrcReg();
1281 VNInfo *Other = LR->valno;
1282 const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1284 if (!OtherMI || !OtherMI->isFullCopy())
1287 unsigned OtherDst = OtherMI->getOperand(0).getReg();
1288 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1290 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1291 !TargetRegisterInfo::isVirtualRegister(OtherDst))
1294 assert(OtherDst == B);
1296 if (Src != OtherSrc)
1299 // If the copies use two different value numbers of X, we cannot merge
1301 LiveInterval &SrcInt = li.getInterval(Src);
1302 // getVNInfoBefore returns NULL for undef copies. In this case, the
1303 // optimization is still safe.
1304 if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1307 DupCopies.push_back(MI);
1312 /// joinIntervals - Attempt to join these two intervals. On failure, this
1314 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1315 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1316 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1318 // If a live interval is a physical register, check for interference with any
1319 // aliases. The interference check implemented here is a bit more conservative
1320 // than the full interfeence check below. We allow overlapping live ranges
1321 // only when one is a copy of the other.
1323 // Optimization for reserved registers like ESP.
1324 // We can only merge with a reserved physreg if RHS has a single value that
1325 // is a copy of CP.DstReg(). The live range of the reserved register will
1326 // look like a set of dead defs - we don't properly track the live range of
1327 // reserved registers.
1328 if (RegClassInfo.isReserved(CP.getDstReg())) {
1329 assert(CP.isFlipped() && RHS.containsOneValue() &&
1330 "Invalid join with reserved register");
1331 // Deny any overlapping intervals. This depends on all the reserved
1332 // register live ranges to look like dead defs.
1333 for (const uint16_t *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1334 if (!LIS->hasInterval(*AS)) {
1335 // Make sure at least DstReg itself exists before attempting a join.
1336 if (*AS == CP.getDstReg())
1337 LIS->getOrCreateInterval(CP.getDstReg());
1340 if (RHS.overlaps(LIS->getInterval(*AS))) {
1341 DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1345 // Skip any value computations, we are not adding new values to the
1346 // reserved register. Also skip merging the live ranges, the reserved
1347 // register live range doesn't need to be accurate as long as all the
1352 // Check if a register mask clobbers DstReg.
1353 BitVector UsableRegs;
1354 if (LIS->checkRegMaskInterference(RHS, UsableRegs) &&
1355 !UsableRegs.test(CP.getDstReg())) {
1356 DEBUG(dbgs() << "\t\tRegister mask interference.\n");
1360 for (const uint16_t *AS = TRI->getAliasSet(CP.getDstReg()); *AS; ++AS){
1361 if (!LIS->hasInterval(*AS))
1363 const LiveInterval &LHS = LIS->getInterval(*AS);
1364 LiveInterval::const_iterator LI = LHS.begin();
1365 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1367 LI = std::lower_bound(LI, LHS.end(), RI->start);
1368 // Does LHS have an overlapping live range starting before RI?
1369 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1370 (RI->start != RI->valno->def ||
1371 !CP.isCoalescable(LIS->getInstructionFromIndex(RI->start)))) {
1373 dbgs() << "\t\tInterference from alias: ";
1374 LHS.print(dbgs(), TRI);
1375 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1380 // Check that LHS ranges beginning in this range are copies.
1381 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1382 if (LI->start != LI->valno->def ||
1383 !CP.isCoalescable(LIS->getInstructionFromIndex(LI->start))) {
1385 dbgs() << "\t\tInterference from alias: ";
1386 LHS.print(dbgs(), TRI);
1387 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1396 // Compute the final value assignment, assuming that the live ranges can be
1398 SmallVector<int, 16> LHSValNoAssignments;
1399 SmallVector<int, 16> RHSValNoAssignments;
1400 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1401 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1402 SmallVector<VNInfo*, 16> NewVNInfo;
1404 SmallVector<MachineInstr*, 8> DupCopies;
1406 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1407 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1409 // Loop over the value numbers of the LHS, seeing if any are defined from
1411 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1414 if (VNI->isUnused() || VNI->isPHIDef())
1416 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1417 assert(MI && "Missing def");
1418 if (!MI->isCopyLike()) // Src not defined by a copy?
1421 // Figure out the value # from the RHS.
1422 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1423 // The copy could be to an aliased physreg.
1426 // DstReg is known to be a register in the LHS interval. If the src is
1427 // from the RHS interval, we can use its value #.
1428 if (!CP.isCoalescable(MI) &&
1429 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1432 LHSValsDefinedFromRHS[VNI] = lr->valno;
1435 // Loop over the value numbers of the RHS, seeing if any are defined from
1437 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1440 if (VNI->isUnused() || VNI->isPHIDef())
1442 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1443 assert(MI && "Missing def");
1444 if (!MI->isCopyLike()) // Src not defined by a copy?
1447 // Figure out the value # from the LHS.
1448 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1449 // The copy could be to an aliased physreg.
1452 // DstReg is known to be a register in the RHS interval. If the src is
1453 // from the LHS interval, we can use its value #.
1454 if (!CP.isCoalescable(MI) &&
1455 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1458 RHSValsDefinedFromLHS[VNI] = lr->valno;
1461 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1462 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1463 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1465 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1468 unsigned VN = VNI->id;
1469 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1471 ComputeUltimateVN(VNI, NewVNInfo,
1472 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1473 LHSValNoAssignments, RHSValNoAssignments);
1475 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1478 unsigned VN = VNI->id;
1479 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1481 // If this value number isn't a copy from the LHS, it's a new number.
1482 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1483 NewVNInfo.push_back(VNI);
1484 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1488 ComputeUltimateVN(VNI, NewVNInfo,
1489 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1490 RHSValNoAssignments, LHSValNoAssignments);
1493 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1494 // interval lists to see if these intervals are coalescable.
1495 LiveInterval::const_iterator I = LHS.begin();
1496 LiveInterval::const_iterator IE = LHS.end();
1497 LiveInterval::const_iterator J = RHS.begin();
1498 LiveInterval::const_iterator JE = RHS.end();
1500 // Skip ahead until the first place of potential sharing.
1501 if (I != IE && J != JE) {
1502 if (I->start < J->start) {
1503 I = std::upper_bound(I, IE, J->start);
1504 if (I != LHS.begin()) --I;
1505 } else if (J->start < I->start) {
1506 J = std::upper_bound(J, JE, I->start);
1507 if (J != RHS.begin()) --J;
1511 while (I != IE && J != JE) {
1512 // Determine if these two live ranges overlap.
1514 if (I->start < J->start) {
1515 Overlaps = I->end > J->start;
1517 Overlaps = J->end > I->start;
1520 // If so, check value # info to determine if they are really different.
1522 // If the live range overlap will map to the same value number in the
1523 // result liverange, we can still coalesce them. If not, we can't.
1524 if (LHSValNoAssignments[I->valno->id] !=
1525 RHSValNoAssignments[J->valno->id])
1529 if (I->end < J->end)
1535 // Update kill info. Some live ranges are extended due to copy coalescing.
1536 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1537 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1538 VNInfo *VNI = I->first;
1539 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1540 if (VNI->hasPHIKill())
1541 NewVNInfo[LHSValID]->setHasPHIKill(true);
1544 // Update kill info. Some live ranges are extended due to copy coalescing.
1545 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1546 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1547 VNInfo *VNI = I->first;
1548 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1549 if (VNI->hasPHIKill())
1550 NewVNInfo[RHSValID]->setHasPHIKill(true);
1553 if (LHSValNoAssignments.empty())
1554 LHSValNoAssignments.push_back(-1);
1555 if (RHSValNoAssignments.empty())
1556 RHSValNoAssignments.push_back(-1);
1558 SmallVector<unsigned, 8> SourceRegisters;
1559 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1560 E = DupCopies.end(); I != E; ++I) {
1561 MachineInstr *MI = *I;
1563 // We have pretended that the assignment to B in
1566 // was actually a copy from A. Now that we decided to coalesce A and B,
1567 // transform the code into
1570 // and mark the X as coalesced to keep the illusion.
1571 unsigned Src = MI->getOperand(1).getReg();
1572 SourceRegisters.push_back(Src);
1573 MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1578 // If B = X was the last use of X in a liverange, we have to shrink it now
1579 // that B = X is gone.
1580 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1581 E = SourceRegisters.end(); I != E; ++I) {
1582 LIS->shrinkToUses(&LIS->getInterval(*I));
1585 // If we get here, we know that we can coalesce the live ranges. Ask the
1586 // intervals to coalesce themselves now.
1587 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1593 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1594 // depth of the basic block (the unsigned), and then on the MBB number.
1595 struct DepthMBBCompare {
1596 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1597 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1598 // Deeper loops first
1599 if (LHS.first != RHS.first)
1600 return LHS.first > RHS.first;
1602 // Prefer blocks that are more connected in the CFG. This takes care of
1603 // the most difficult copies first while intervals are short.
1604 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1605 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1609 // As a last resort, sort by block number.
1610 return LHS.second->getNumber() < RHS.second->getNumber();
1616 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB,
1617 std::vector<MachineInstr*> &TryAgain) {
1618 DEBUG(dbgs() << MBB->getName() << ":\n");
1620 SmallVector<MachineInstr*, 8> VirtCopies;
1621 SmallVector<MachineInstr*, 8> PhysCopies;
1622 SmallVector<MachineInstr*, 8> ImpDefCopies;
1623 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1625 MachineInstr *Inst = MII++;
1627 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1628 unsigned SrcReg, DstReg;
1629 if (Inst->isCopy()) {
1630 DstReg = Inst->getOperand(0).getReg();
1631 SrcReg = Inst->getOperand(1).getReg();
1632 } else if (Inst->isSubregToReg()) {
1633 DstReg = Inst->getOperand(0).getReg();
1634 SrcReg = Inst->getOperand(2).getReg();
1638 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1639 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1640 if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1641 ImpDefCopies.push_back(Inst);
1642 else if (SrcIsPhys || DstIsPhys)
1643 PhysCopies.push_back(Inst);
1645 VirtCopies.push_back(Inst);
1648 // Try coalescing implicit copies and insert_subreg <undef> first,
1649 // followed by copies to / from physical registers, then finally copies
1650 // from virtual registers to virtual registers.
1651 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1652 MachineInstr *TheCopy = ImpDefCopies[i];
1654 if (!joinCopy(TheCopy, Again))
1656 TryAgain.push_back(TheCopy);
1658 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1659 MachineInstr *TheCopy = PhysCopies[i];
1661 if (!joinCopy(TheCopy, Again))
1663 TryAgain.push_back(TheCopy);
1665 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1666 MachineInstr *TheCopy = VirtCopies[i];
1668 if (!joinCopy(TheCopy, Again))
1670 TryAgain.push_back(TheCopy);
1674 void RegisterCoalescer::joinAllIntervals() {
1675 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1677 std::vector<MachineInstr*> TryAgainList;
1678 if (Loops->empty()) {
1679 // If there are no loops in the function, join intervals in function order.
1680 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1682 copyCoalesceInMBB(I, TryAgainList);
1684 // Otherwise, join intervals in inner loops before other intervals.
1685 // Unfortunately we can't just iterate over loop hierarchy here because
1686 // there may be more MBB's than BB's. Collect MBB's for sorting.
1688 // Join intervals in the function prolog first. We want to join physical
1689 // registers with virtual registers before the intervals got too long.
1690 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1691 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1692 MachineBasicBlock *MBB = I;
1693 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1696 // Sort by loop depth.
1697 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1699 // Finally, join intervals in loop nest order.
1700 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1701 copyCoalesceInMBB(MBBs[i].second, TryAgainList);
1704 // Joining intervals can allow other intervals to be joined. Iteratively join
1705 // until we make no progress.
1706 bool ProgressMade = true;
1707 while (ProgressMade) {
1708 ProgressMade = false;
1710 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1711 MachineInstr *&TheCopy = TryAgainList[i];
1716 bool Success = joinCopy(TheCopy, Again);
1717 if (Success || !Again) {
1718 TheCopy= 0; // Mark this one as done.
1719 ProgressMade = true;
1725 void RegisterCoalescer::releaseMemory() {
1726 JoinedCopies.clear();
1727 ReMatCopies.clear();
1731 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1733 MRI = &fn.getRegInfo();
1734 TM = &fn.getTarget();
1735 TRI = TM->getRegisterInfo();
1736 TII = TM->getInstrInfo();
1737 LIS = &getAnalysis<LiveIntervals>();
1738 LDV = &getAnalysis<LiveDebugVariables>();
1739 AA = &getAnalysis<AliasAnalysis>();
1740 Loops = &getAnalysis<MachineLoopInfo>();
1742 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1743 << "********** Function: "
1744 << ((Value*)MF->getFunction())->getName() << '\n');
1746 if (VerifyCoalescing)
1747 MF->verify(this, "Before register coalescing");
1749 RegClassInfo.runOnMachineFunction(fn);
1751 // Join (coalesce) intervals if requested.
1752 if (EnableJoining) {
1755 dbgs() << "********** INTERVALS POST JOINING **********\n";
1756 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1758 I->second->print(dbgs(), TRI);
1764 // Perform a final pass over the instructions and compute spill weights
1765 // and remove identity moves.
1766 SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1767 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1768 mbbi != mbbe; ++mbbi) {
1769 MachineBasicBlock* mbb = mbbi;
1770 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1772 MachineInstr *MI = mii;
1773 if (JoinedCopies.count(MI)) {
1774 // Delete all coalesced copies.
1775 bool DoDelete = true;
1776 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1777 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1778 unsigned DstReg = MI->getOperand(0).getReg();
1780 // Collect candidates for register class inflation.
1781 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1782 RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1783 InflateRegs.push_back(SrcReg);
1784 if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1785 RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1786 InflateRegs.push_back(DstReg);
1788 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1789 MI->getNumOperands() > 2)
1790 // Do not delete extract_subreg, insert_subreg of physical
1791 // registers unless the definition is dead. e.g.
1792 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1793 // or else the scavenger may complain. LowerSubregs will
1794 // delete them later.
1797 if (MI->allDefsAreDead()) {
1798 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1799 LIS->hasInterval(SrcReg))
1800 LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1804 // We need the instruction to adjust liveness, so make it a KILL.
1805 if (MI->isSubregToReg()) {
1806 MI->RemoveOperand(3);
1807 MI->RemoveOperand(1);
1809 MI->setDesc(TII->get(TargetOpcode::KILL));
1810 mii = llvm::next(mii);
1812 LIS->RemoveMachineInstrFromMaps(MI);
1813 mii = mbbi->erase(mii);
1819 // Now check if this is a remat'ed def instruction which is now dead.
1820 if (ReMatDefs.count(MI)) {
1822 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1823 const MachineOperand &MO = MI->getOperand(i);
1826 unsigned Reg = MO.getReg();
1829 DeadDefs.push_back(Reg);
1830 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1831 // Remat may also enable register class inflation.
1832 if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1833 InflateRegs.push_back(Reg);
1837 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1838 !MRI->use_nodbg_empty(Reg)) {
1844 while (!DeadDefs.empty()) {
1845 unsigned DeadDef = DeadDefs.back();
1846 DeadDefs.pop_back();
1847 removeDeadDef(LIS->getInterval(DeadDef), MI);
1849 LIS->RemoveMachineInstrFromMaps(mii);
1850 mii = mbbi->erase(mii);
1858 // Check for now unnecessary kill flags.
1859 if (LIS->isNotInMIMap(MI)) continue;
1860 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1861 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1862 MachineOperand &MO = MI->getOperand(i);
1863 if (!MO.isReg() || !MO.isKill()) continue;
1864 unsigned reg = MO.getReg();
1865 if (!reg || !LIS->hasInterval(reg)) continue;
1866 if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1867 MO.setIsKill(false);
1870 // When leaving a kill flag on a physreg, check if any subregs should
1872 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1874 for (const uint16_t *SR = TRI->getSubRegisters(reg);
1875 unsigned S = *SR; ++SR)
1876 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1877 MI->addRegisterDefined(S, TRI);
1882 // After deleting a lot of copies, register classes may be less constrained.
1883 // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1885 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1886 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1888 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1889 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1890 unsigned Reg = InflateRegs[i];
1891 if (MRI->reg_nodbg_empty(Reg))
1893 if (MRI->recomputeRegClass(Reg, *TM)) {
1894 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1895 << MRI->getRegClass(Reg)->getName() << '\n');
1902 if (VerifyCoalescing)
1903 MF->verify(this, "After register coalescing");
1907 /// print - Implement the dump method.
1908 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {