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 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
153 /// update the subregister number if it is not zero. If DstReg is a
154 /// physical register and the existing subregister number of the def / use
155 /// being updated is not zero, make sure to set it to the correct physical
157 void UpdateRegDefsUses(const CoalescerPair &CP);
159 /// RemoveDeadDef - If a def of a live interval is now determined dead,
160 /// remove the val# it defines. If the live interval becomes empty, remove
162 bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
164 /// markAsJoined - Remember that CopyMI has already been joined.
165 void markAsJoined(MachineInstr *CopyMI);
167 /// eliminateUndefCopy - Handle copies of undef values.
168 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
171 static char ID; // Class identification, replacement for typeinfo
172 RegisterCoalescer() : MachineFunctionPass(ID) {
173 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
176 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
178 virtual void releaseMemory();
180 /// runOnMachineFunction - pass entry point
181 virtual bool runOnMachineFunction(MachineFunction&);
183 /// print - Implement the dump method.
184 virtual void print(raw_ostream &O, const Module* = 0) const;
186 } /// end anonymous namespace
188 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
190 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
191 "Simple Register Coalescing", false, false)
192 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
193 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
194 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
195 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
196 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
197 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
198 "Simple Register Coalescing", false, false)
200 char RegisterCoalescer::ID = 0;
202 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
205 return tri.composeSubRegIndices(a, b);
208 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
209 unsigned &Src, unsigned &Dst,
210 unsigned &SrcSub, unsigned &DstSub) {
212 Dst = MI->getOperand(0).getReg();
213 DstSub = MI->getOperand(0).getSubReg();
214 Src = MI->getOperand(1).getReg();
215 SrcSub = MI->getOperand(1).getSubReg();
216 } else if (MI->isSubregToReg()) {
217 Dst = MI->getOperand(0).getReg();
218 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
219 MI->getOperand(3).getImm());
220 Src = MI->getOperand(2).getReg();
221 SrcSub = MI->getOperand(2).getSubReg();
227 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
228 SrcReg = DstReg = SubIdx = 0;
230 Flipped = CrossClass = false;
232 unsigned Src, Dst, SrcSub, DstSub;
233 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
235 Partial = SrcSub || DstSub;
237 // If one register is a physreg, it must be Dst.
238 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
239 if (TargetRegisterInfo::isPhysicalRegister(Dst))
242 std::swap(SrcSub, DstSub);
246 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
248 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
249 // Eliminate DstSub on a physreg.
251 Dst = TRI.getSubReg(Dst, DstSub);
252 if (!Dst) return false;
256 // Eliminate SrcSub by picking a corresponding Dst superregister.
258 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
259 if (!Dst) return false;
261 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
265 // Both registers are virtual.
267 // Both registers have subreg indices.
268 if (SrcSub && DstSub) {
269 // For now we only handle the case of identical indices in commensurate
270 // registers: Dreg:ssub_1 + Dreg:ssub_1 -> Dreg
271 // FIXME: Handle Qreg:ssub_3 + Dreg:ssub_1 as QReg:dsub_1 + Dreg.
272 if (SrcSub != DstSub)
274 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
275 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
276 if (!TRI.getCommonSubClass(DstRC, SrcRC))
281 // There can be no SrcSub.
286 assert(!Flipped && "Unexpected flip");
290 // Find the new register class.
291 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
292 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
294 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
296 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
299 CrossClass = NewRC != DstRC || NewRC != SrcRC;
301 // Check our invariants
302 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
303 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
304 "Cannot have a physical SubIdx");
311 bool CoalescerPair::flip() {
312 if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg))
314 std::swap(SrcReg, DstReg);
319 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
322 unsigned Src, Dst, SrcSub, DstSub;
323 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
326 // Find the virtual register that is SrcReg.
329 std::swap(SrcSub, DstSub);
330 } else if (Src != SrcReg) {
334 // Now check that Dst matches DstReg.
335 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
336 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
338 assert(!SubIdx && "Inconsistent CoalescerPair state.");
339 // DstSub could be set for a physreg from INSERT_SUBREG.
341 Dst = TRI.getSubReg(Dst, DstSub);
344 return DstReg == Dst;
345 // This is a partial register copy. Check that the parts match.
346 return TRI.getSubReg(DstReg, SrcSub) == Dst;
348 // DstReg is virtual.
351 // Registers match, do the subregisters line up?
352 return compose(TRI, SubIdx, SrcSub) == DstSub;
356 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
357 AU.setPreservesCFG();
358 AU.addRequired<AliasAnalysis>();
359 AU.addRequired<LiveIntervals>();
360 AU.addPreserved<LiveIntervals>();
361 AU.addRequired<LiveDebugVariables>();
362 AU.addPreserved<LiveDebugVariables>();
363 AU.addPreserved<SlotIndexes>();
364 AU.addRequired<MachineLoopInfo>();
365 AU.addPreserved<MachineLoopInfo>();
366 AU.addPreservedID(MachineDominatorsID);
367 MachineFunctionPass::getAnalysisUsage(AU);
370 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
371 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
372 JoinedCopies.insert(CopyMI);
374 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
375 /// code elimination.
376 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
377 E = CopyMI->operands_end(); I != E; ++I)
382 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
383 /// being the source and IntB being the dest, thus this defines a value number
384 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
385 /// see if we can merge these two pieces of B into a single value number,
386 /// eliminating a copy. For example:
390 /// B1 = A3 <- this copy
392 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
393 /// value number to be replaced with B0 (which simplifies the B liveinterval).
395 /// This returns true if an interval was modified.
397 bool RegisterCoalescer::AdjustCopiesBackFrom(const CoalescerPair &CP,
398 MachineInstr *CopyMI) {
399 // Bail if there is no dst interval - can happen when merging physical subreg
401 if (!LIS->hasInterval(CP.getDstReg()))
405 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
407 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
408 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
410 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
411 // the example above.
412 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
413 if (BLR == IntB.end()) return false;
414 VNInfo *BValNo = BLR->valno;
416 // Get the location that B is defined at. Two options: either this value has
417 // an unknown definition point or it is defined at CopyIdx. If unknown, we
419 if (BValNo->def != CopyIdx) return false;
421 // AValNo is the value number in A that defines the copy, A3 in the example.
422 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
423 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
424 // The live range might not exist after fun with physreg coalescing.
425 if (ALR == IntA.end()) return false;
426 VNInfo *AValNo = ALR->valno;
428 // If AValNo is defined as a copy from IntB, we can potentially process this.
429 // Get the instruction that defines this value number.
430 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
431 if (!CP.isCoalescable(ACopyMI))
434 // Get the LiveRange in IntB that this value number starts with.
435 LiveInterval::iterator ValLR =
436 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
437 if (ValLR == IntB.end())
440 // Make sure that the end of the live range is inside the same block as
442 MachineInstr *ValLREndInst =
443 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
444 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
447 // Okay, we now know that ValLR ends in the same block that the CopyMI
448 // live-range starts. If there are no intervening live ranges between them in
449 // IntB, we can merge them.
450 if (ValLR+1 != BLR) return false;
452 // If a live interval is a physical register, conservatively check if any
453 // of its aliases is overlapping the live interval of the virtual register.
454 // If so, do not coalesce.
455 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
456 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
457 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
459 dbgs() << "\t\tInterfere with alias ";
460 LIS->getInterval(*AS).print(dbgs(), TRI);
467 dbgs() << "Extending: ";
468 IntB.print(dbgs(), TRI);
471 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
472 // We are about to delete CopyMI, so need to remove it as the 'instruction
473 // that defines this value #'. Update the valnum with the new defining
475 BValNo->def = FillerStart;
477 // Okay, we can merge them. We need to insert a new liverange:
478 // [ValLR.end, BLR.begin) of either value number, then we merge the
479 // two value numbers.
480 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
482 // If the IntB live range is assigned to a physical register, and if that
483 // physreg has sub-registers, update their live intervals as well.
484 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
485 for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
486 if (!LIS->hasInterval(*SR))
488 LiveInterval &SRLI = LIS->getInterval(*SR);
489 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
490 SRLI.getNextValue(FillerStart,
491 LIS->getVNInfoAllocator())));
495 // Okay, merge "B1" into the same value number as "B0".
496 if (BValNo != ValLR->valno) {
497 // If B1 is killed by a PHI, then the merged live range must also be killed
498 // by the same PHI, as B0 and B1 can not overlap.
499 bool HasPHIKill = BValNo->hasPHIKill();
500 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
502 ValLR->valno->setHasPHIKill(true);
505 dbgs() << " result = ";
506 IntB.print(dbgs(), TRI);
510 // If the source instruction was killing the source register before the
511 // merge, unset the isKill marker given the live range has been extended.
512 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
514 ValLREndInst->getOperand(UIdx).setIsKill(false);
517 // Rewrite the copy. If the copy instruction was killing the destination
518 // register before the merge, find the last use and trim the live range. That
519 // will also add the isKill marker.
520 CopyMI->substituteRegister(IntA.reg, IntB.reg, CP.getSubIdx(),
522 if (ALR->end == CopyIdx)
523 LIS->shrinkToUses(&IntA);
529 /// HasOtherReachingDefs - Return true if there are definitions of IntB
530 /// other than BValNo val# that can reach uses of AValno val# of IntA.
531 bool RegisterCoalescer::HasOtherReachingDefs(LiveInterval &IntA,
535 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
537 if (AI->valno != AValNo) continue;
538 LiveInterval::Ranges::iterator BI =
539 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
540 if (BI != IntB.ranges.begin())
542 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
543 if (BI->valno == BValNo)
545 if (BI->start <= AI->start && BI->end > AI->start)
547 if (BI->start > AI->start && BI->start < AI->end)
554 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
555 /// IntA being the source and IntB being the dest, thus this defines a value
556 /// number in IntB. If the source value number (in IntA) is defined by a
557 /// commutable instruction and its other operand is coalesced to the copy dest
558 /// register, see if we can transform the copy into a noop by commuting the
559 /// definition. For example,
561 /// A3 = op A2 B0<kill>
563 /// B1 = A3 <- this copy
565 /// = op A3 <- more uses
569 /// B2 = op B0 A2<kill>
571 /// B1 = B2 <- now an identify copy
573 /// = op B2 <- more uses
575 /// This returns true if an interval was modified.
577 bool RegisterCoalescer::RemoveCopyByCommutingDef(const CoalescerPair &CP,
578 MachineInstr *CopyMI) {
579 // FIXME: For now, only eliminate the copy by commuting its def when the
580 // source register is a virtual register. We want to guard against cases
581 // where the copy is a back edge copy and commuting the def lengthen the
582 // live interval of the source register to the entire loop.
583 if (CP.isPhys() && CP.isFlipped())
586 // Bail if there is no dst interval.
587 if (!LIS->hasInterval(CP.getDstReg()))
590 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
593 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
595 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
597 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
598 // the example above.
599 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
600 if (!BValNo || BValNo->def != CopyIdx)
603 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
605 // AValNo is the value number in A that defines the copy, A3 in the example.
606 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
607 assert(AValNo && "COPY source not live");
609 // If other defs can reach uses of this def, then it's not safe to perform
611 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
613 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
616 if (!DefMI->isCommutable())
618 // If DefMI is a two-address instruction then commuting it will change the
619 // destination register.
620 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
621 assert(DefIdx != -1);
623 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
625 unsigned Op1, Op2, NewDstIdx;
626 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
630 else if (Op2 == UseOpIdx)
635 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
636 unsigned NewReg = NewDstMO.getReg();
637 if (NewReg != IntB.reg || !NewDstMO.isKill())
640 // Make sure there are no other definitions of IntB that would reach the
641 // uses which the new definition can reach.
642 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
645 // Abort if the aliases of IntB.reg have values that are not simply the
646 // clobbers from the superreg.
647 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
648 for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
649 if (LIS->hasInterval(*AS) &&
650 HasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
653 // If some of the uses of IntA.reg is already coalesced away, return false.
654 // It's not possible to determine whether it's safe to perform the coalescing.
655 for (MachineRegisterInfo::use_nodbg_iterator UI =
656 MRI->use_nodbg_begin(IntA.reg),
657 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
658 MachineInstr *UseMI = &*UI;
659 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
660 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
661 if (ULR == IntA.end())
663 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
667 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
670 // At this point we have decided that it is legal to do this
671 // transformation. Start by commuting the instruction.
672 MachineBasicBlock *MBB = DefMI->getParent();
673 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
676 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
677 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
678 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
680 if (NewMI != DefMI) {
681 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
682 MachineBasicBlock::iterator Pos = DefMI;
683 MBB->insert(Pos, NewMI);
686 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
687 NewMI->getOperand(OpIdx).setIsKill();
689 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
698 // Update uses of IntA of the specific Val# with IntB.
699 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
700 UE = MRI->use_end(); UI != UE;) {
701 MachineOperand &UseMO = UI.getOperand();
702 MachineInstr *UseMI = &*UI;
704 if (JoinedCopies.count(UseMI))
706 if (UseMI->isDebugValue()) {
707 // FIXME These don't have an instruction index. Not clear we have enough
708 // info to decide whether to do this replacement or not. For now do it.
709 UseMO.setReg(NewReg);
712 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
713 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
714 if (ULR == IntA.end() || ULR->valno != AValNo)
716 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
717 UseMO.substPhysReg(NewReg, *TRI);
719 UseMO.setReg(NewReg);
722 if (!UseMI->isCopy())
724 if (UseMI->getOperand(0).getReg() != IntB.reg ||
725 UseMI->getOperand(0).getSubReg())
728 // This copy will become a noop. If it's defining a new val#, merge it into
730 SlotIndex DefIdx = UseIdx.getRegSlot();
731 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
734 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
735 assert(DVNI->def == DefIdx);
736 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
740 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
742 VNInfo *ValNo = BValNo;
743 ValNo->def = AValNo->def;
744 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
746 if (AI->valno != AValNo) continue;
747 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
749 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
751 IntA.removeValNo(AValNo);
752 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
757 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
758 /// computation, replace the copy by rematerialize the definition.
759 bool RegisterCoalescer::ReMaterializeTrivialDef(LiveInterval &SrcInt,
762 MachineInstr *CopyMI) {
763 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
764 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
765 assert(SrcLR != SrcInt.end() && "Live range not found!");
766 VNInfo *ValNo = SrcLR->valno;
767 if (ValNo->isPHIDef() || ValNo->isUnused())
769 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
772 assert(DefMI && "Defining instruction disappeared");
773 if (!DefMI->isAsCheapAsAMove())
775 if (!TII->isTriviallyReMaterializable(DefMI, AA))
777 bool SawStore = false;
778 if (!DefMI->isSafeToMove(TII, AA, SawStore))
780 const MCInstrDesc &MCID = DefMI->getDesc();
781 if (MCID.getNumDefs() != 1)
783 if (!DefMI->isImplicitDef()) {
784 // Make sure the copy destination register class fits the instruction
785 // definition register class. The mismatch can happen as a result of earlier
786 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
787 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI);
788 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
789 if (MRI->getRegClass(DstReg) != RC)
791 } else if (!RC->contains(DstReg))
795 MachineBasicBlock *MBB = CopyMI->getParent();
796 MachineBasicBlock::iterator MII =
797 llvm::next(MachineBasicBlock::iterator(CopyMI));
798 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
799 MachineInstr *NewMI = prior(MII);
801 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
802 // We need to remember these so we can add intervals once we insert
803 // NewMI into SlotIndexes.
804 SmallVector<unsigned, 4> NewMIImplDefs;
805 for (unsigned i = NewMI->getDesc().getNumOperands(),
806 e = NewMI->getNumOperands(); i != e; ++i) {
807 MachineOperand &MO = NewMI->getOperand(i);
809 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
810 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
811 NewMIImplDefs.push_back(MO.getReg());
815 // CopyMI may have implicit operands, transfer them over to the newly
816 // rematerialized instruction. And update implicit def interval valnos.
817 for (unsigned i = CopyMI->getDesc().getNumOperands(),
818 e = CopyMI->getNumOperands(); i != e; ++i) {
819 MachineOperand &MO = CopyMI->getOperand(i);
821 assert(MO.isImplicit() && "No explicit operands after implict operands.");
822 // Discard VReg implicit defs.
823 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
824 NewMI->addOperand(MO);
829 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
831 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
832 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
833 unsigned reg = NewMIImplDefs[i];
834 LiveInterval &li = LIS->getInterval(reg);
835 VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
836 LIS->getVNInfoAllocator());
837 LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
841 CopyMI->eraseFromParent();
842 ReMatCopies.insert(CopyMI);
843 ReMatDefs.insert(DefMI);
844 DEBUG(dbgs() << "Remat: " << *NewMI);
847 // The source interval can become smaller because we removed a use.
849 LIS->shrinkToUses(&SrcInt);
854 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
855 /// values, it only removes local variables. When we have a copy like:
857 /// %vreg1 = COPY %vreg2<undef>
859 /// We delete the copy and remove the corresponding value number from %vreg1.
860 /// Any uses of that value number are marked as <undef>.
861 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
862 const CoalescerPair &CP) {
863 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
864 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
865 if (SrcInt->liveAt(Idx))
867 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
868 if (DstInt->liveAt(Idx))
871 // No intervals are live-in to CopyMI - it is undef.
876 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
877 assert(DeadVNI && "No value defined in DstInt");
878 DstInt->removeValNo(DeadVNI);
880 // Find new undef uses.
881 for (MachineRegisterInfo::reg_nodbg_iterator
882 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
884 MachineOperand &MO = I.getOperand();
885 if (MO.isDef() || MO.isUndef())
887 MachineInstr *MI = MO.getParent();
888 SlotIndex Idx = LIS->getInstructionIndex(MI);
889 if (DstInt->liveAt(Idx))
892 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
897 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
898 /// update the subregister number if it is not zero. If DstReg is a
899 /// physical register and the existing subregister number of the def / use
900 /// being updated is not zero, make sure to set it to the correct physical
903 RegisterCoalescer::UpdateRegDefsUses(const CoalescerPair &CP) {
904 bool DstIsPhys = CP.isPhys();
905 unsigned SrcReg = CP.getSrcReg();
906 unsigned DstReg = CP.getDstReg();
907 unsigned SubIdx = CP.getSubIdx();
909 // Update LiveDebugVariables.
910 LDV->renameRegister(SrcReg, DstReg, SubIdx);
912 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
913 MachineInstr *UseMI = I.skipInstruction();) {
914 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
917 if (UseMI->isFullCopy() &&
918 UseMI->getOperand(1).getReg() == SrcReg &&
919 UseMI->getOperand(0).getReg() != SrcReg &&
920 UseMI->getOperand(0).getReg() != DstReg &&
921 !JoinedCopies.count(UseMI) &&
922 ReMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
923 UseMI->getOperand(0).getReg(), UseMI))
927 SmallVector<unsigned,8> Ops;
929 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
931 // Replace SrcReg with DstReg in all UseMI operands.
932 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
933 MachineOperand &MO = UseMI->getOperand(Ops[i]);
935 // Make sure we don't create read-modify-write defs accidentally. We
936 // assume here that a SrcReg def cannot be joined into a live DstReg. If
937 // RegisterCoalescer starts tracking partially live registers, we will
938 // need to check the actual LiveInterval to determine if DstReg is live
940 if (SubIdx && !Reads)
944 MO.substPhysReg(DstReg, *TRI);
946 MO.substVirtReg(DstReg, SubIdx, *TRI);
949 // This instruction is a copy that will be removed.
950 if (JoinedCopies.count(UseMI))
954 dbgs() << "\t\tupdated: ";
955 if (!UseMI->isDebugValue())
956 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
962 /// removeIntervalIfEmpty - Check if the live interval of a physical register
963 /// is empty, if so remove it and also remove the empty intervals of its
964 /// sub-registers. Return true if live interval is removed.
965 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
966 const TargetRegisterInfo *TRI) {
968 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
969 for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
970 if (!LIS->hasInterval(*SR))
972 LiveInterval &sli = LIS->getInterval(*SR);
974 LIS->removeInterval(*SR);
976 LIS->removeInterval(li.reg);
982 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
983 /// the val# it defines. If the live interval becomes empty, remove it as well.
984 bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li,
985 MachineInstr *DefMI) {
986 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
987 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
988 if (DefIdx != MLR->valno->def)
990 li.removeValNo(MLR->valno);
991 return removeIntervalIfEmpty(li, LIS, TRI);
994 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
995 /// We need to be careful about coalescing a source physical register with a
996 /// virtual register. Once the coalescing is done, it cannot be broken and these
997 /// are not spillable! If the destination interval uses are far away, think
998 /// twice about coalescing them!
999 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1000 bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1001 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1003 /// Always join simple intervals that are defined by a single copy from a
1004 /// reserved register. This doesn't increase register pressure, so it is
1005 /// always beneficial.
1006 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1009 if (!EnablePhysicalJoin) {
1010 DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1014 // Only coalesce to allocatable physreg, we don't want to risk modifying
1015 // reserved registers.
1017 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1018 return false; // Not coalescable.
1021 // Don't join with physregs that have a ridiculous number of live
1022 // ranges. The data structure performance is really bad when that
1024 if (LIS->hasInterval(CP.getDstReg()) &&
1025 LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1028 << "\tPhysical register live interval too complicated, abort!\n");
1032 // FIXME: Why are we skipping this test for partial copies?
1033 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1034 if (!CP.isPartial()) {
1035 const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1036 unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1037 unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1038 if (Length > Threshold) {
1040 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1048 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1049 /// which are the src/dst of the copy instruction CopyMI. This returns true
1050 /// if the copy was successfully coalesced away. If it is not currently
1051 /// possible to coalesce this interval, but it may be possible if other
1052 /// things get coalesced, then it returns true by reference in 'Again'.
1053 bool RegisterCoalescer::JoinCopy(MachineInstr *CopyMI, bool &Again) {
1056 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1057 return false; // Already done.
1059 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1061 CoalescerPair CP(*TII, *TRI);
1062 if (!CP.setRegisters(CopyMI)) {
1063 DEBUG(dbgs() << "\tNot coalescable.\n");
1067 // If they are already joined we continue.
1068 if (CP.getSrcReg() == CP.getDstReg()) {
1069 markAsJoined(CopyMI);
1070 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1071 return false; // Not coalescable.
1074 // Eliminate undefs.
1075 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1076 markAsJoined(CopyMI);
1077 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1078 return false; // Not coalescable.
1081 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1082 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1085 // Enforce policies.
1087 if (!shouldJoinPhys(CP)) {
1088 // Before giving up coalescing, if definition of source is defined by
1089 // trivial computation, try rematerializing it.
1090 if (!CP.isFlipped() &&
1091 ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1092 CP.getDstReg(), CopyMI))
1097 // Avoid constraining virtual register regclass too much.
1098 if (CP.isCrossClass()) {
1099 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1100 if (DisableCrossClassJoin) {
1101 DEBUG(dbgs() << "\tCross-class joins disabled.\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();
1615 void RegisterCoalescer::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1616 std::vector<MachineInstr*> &TryAgain) {
1617 DEBUG(dbgs() << MBB->getName() << ":\n");
1619 SmallVector<MachineInstr*, 8> VirtCopies;
1620 SmallVector<MachineInstr*, 8> PhysCopies;
1621 SmallVector<MachineInstr*, 8> ImpDefCopies;
1622 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1624 MachineInstr *Inst = MII++;
1626 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1627 unsigned SrcReg, DstReg;
1628 if (Inst->isCopy()) {
1629 DstReg = Inst->getOperand(0).getReg();
1630 SrcReg = Inst->getOperand(1).getReg();
1631 } else if (Inst->isSubregToReg()) {
1632 DstReg = Inst->getOperand(0).getReg();
1633 SrcReg = Inst->getOperand(2).getReg();
1637 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1638 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1639 if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1640 ImpDefCopies.push_back(Inst);
1641 else if (SrcIsPhys || DstIsPhys)
1642 PhysCopies.push_back(Inst);
1644 VirtCopies.push_back(Inst);
1647 // Try coalescing implicit copies and insert_subreg <undef> first,
1648 // followed by copies to / from physical registers, then finally copies
1649 // from virtual registers to virtual registers.
1650 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1651 MachineInstr *TheCopy = ImpDefCopies[i];
1653 if (!JoinCopy(TheCopy, Again))
1655 TryAgain.push_back(TheCopy);
1657 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1658 MachineInstr *TheCopy = PhysCopies[i];
1660 if (!JoinCopy(TheCopy, Again))
1662 TryAgain.push_back(TheCopy);
1664 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1665 MachineInstr *TheCopy = VirtCopies[i];
1667 if (!JoinCopy(TheCopy, Again))
1669 TryAgain.push_back(TheCopy);
1673 void RegisterCoalescer::joinIntervals() {
1674 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1676 std::vector<MachineInstr*> TryAgainList;
1677 if (Loops->empty()) {
1678 // If there are no loops in the function, join intervals in function order.
1679 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1681 CopyCoalesceInMBB(I, TryAgainList);
1683 // Otherwise, join intervals in inner loops before other intervals.
1684 // Unfortunately we can't just iterate over loop hierarchy here because
1685 // there may be more MBB's than BB's. Collect MBB's for sorting.
1687 // Join intervals in the function prolog first. We want to join physical
1688 // registers with virtual registers before the intervals got too long.
1689 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1690 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1691 MachineBasicBlock *MBB = I;
1692 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1695 // Sort by loop depth.
1696 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1698 // Finally, join intervals in loop nest order.
1699 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1700 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1703 // Joining intervals can allow other intervals to be joined. Iteratively join
1704 // until we make no progress.
1705 bool ProgressMade = true;
1706 while (ProgressMade) {
1707 ProgressMade = false;
1709 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1710 MachineInstr *&TheCopy = TryAgainList[i];
1715 bool Success = JoinCopy(TheCopy, Again);
1716 if (Success || !Again) {
1717 TheCopy= 0; // Mark this one as done.
1718 ProgressMade = true;
1724 void RegisterCoalescer::releaseMemory() {
1725 JoinedCopies.clear();
1726 ReMatCopies.clear();
1730 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1732 MRI = &fn.getRegInfo();
1733 TM = &fn.getTarget();
1734 TRI = TM->getRegisterInfo();
1735 TII = TM->getInstrInfo();
1736 LIS = &getAnalysis<LiveIntervals>();
1737 LDV = &getAnalysis<LiveDebugVariables>();
1738 AA = &getAnalysis<AliasAnalysis>();
1739 Loops = &getAnalysis<MachineLoopInfo>();
1741 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1742 << "********** Function: "
1743 << ((Value*)MF->getFunction())->getName() << '\n');
1745 if (VerifyCoalescing)
1746 MF->verify(this, "Before register coalescing");
1748 RegClassInfo.runOnMachineFunction(fn);
1750 // Join (coalesce) intervals if requested.
1751 if (EnableJoining) {
1754 dbgs() << "********** INTERVALS POST JOINING **********\n";
1755 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1757 I->second->print(dbgs(), TRI);
1763 // Perform a final pass over the instructions and compute spill weights
1764 // and remove identity moves.
1765 SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1766 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1767 mbbi != mbbe; ++mbbi) {
1768 MachineBasicBlock* mbb = mbbi;
1769 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1771 MachineInstr *MI = mii;
1772 if (JoinedCopies.count(MI)) {
1773 // Delete all coalesced copies.
1774 bool DoDelete = true;
1775 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1776 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1777 unsigned DstReg = MI->getOperand(0).getReg();
1779 // Collect candidates for register class inflation.
1780 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1781 RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1782 InflateRegs.push_back(SrcReg);
1783 if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1784 RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1785 InflateRegs.push_back(DstReg);
1787 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1788 MI->getNumOperands() > 2)
1789 // Do not delete extract_subreg, insert_subreg of physical
1790 // registers unless the definition is dead. e.g.
1791 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1792 // or else the scavenger may complain. LowerSubregs will
1793 // delete them later.
1796 if (MI->allDefsAreDead()) {
1797 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1798 LIS->hasInterval(SrcReg))
1799 LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1803 // We need the instruction to adjust liveness, so make it a KILL.
1804 if (MI->isSubregToReg()) {
1805 MI->RemoveOperand(3);
1806 MI->RemoveOperand(1);
1808 MI->setDesc(TII->get(TargetOpcode::KILL));
1809 mii = llvm::next(mii);
1811 LIS->RemoveMachineInstrFromMaps(MI);
1812 mii = mbbi->erase(mii);
1818 // Now check if this is a remat'ed def instruction which is now dead.
1819 if (ReMatDefs.count(MI)) {
1821 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1822 const MachineOperand &MO = MI->getOperand(i);
1825 unsigned Reg = MO.getReg();
1828 DeadDefs.push_back(Reg);
1829 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1830 // Remat may also enable register class inflation.
1831 if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1832 InflateRegs.push_back(Reg);
1836 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1837 !MRI->use_nodbg_empty(Reg)) {
1843 while (!DeadDefs.empty()) {
1844 unsigned DeadDef = DeadDefs.back();
1845 DeadDefs.pop_back();
1846 RemoveDeadDef(LIS->getInterval(DeadDef), MI);
1848 LIS->RemoveMachineInstrFromMaps(mii);
1849 mii = mbbi->erase(mii);
1857 // Check for now unnecessary kill flags.
1858 if (LIS->isNotInMIMap(MI)) continue;
1859 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1860 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1861 MachineOperand &MO = MI->getOperand(i);
1862 if (!MO.isReg() || !MO.isKill()) continue;
1863 unsigned reg = MO.getReg();
1864 if (!reg || !LIS->hasInterval(reg)) continue;
1865 if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1866 MO.setIsKill(false);
1869 // When leaving a kill flag on a physreg, check if any subregs should
1871 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1873 for (const uint16_t *SR = TRI->getSubRegisters(reg);
1874 unsigned S = *SR; ++SR)
1875 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1876 MI->addRegisterDefined(S, TRI);
1881 // After deleting a lot of copies, register classes may be less constrained.
1882 // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1884 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1885 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1887 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1888 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1889 unsigned Reg = InflateRegs[i];
1890 if (MRI->reg_nodbg_empty(Reg))
1892 if (MRI->recomputeRegClass(Reg, *TM)) {
1893 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1894 << MRI->getRegClass(Reg)->getName() << '\n');
1901 if (VerifyCoalescing)
1902 MF->verify(this, "After register coalescing");
1906 /// print - Implement the dump method.
1907 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {