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 "VirtRegMap.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Value.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveRangeEdit.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegisterClassInfo.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/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
52 STATISTIC(numJoins , "Number of interval joins performed");
53 STATISTIC(numCrossRCs , "Number of cross class joins performed");
54 STATISTIC(numCommutes , "Number of instruction commuting performed");
55 STATISTIC(numExtends , "Number of copies extended");
56 STATISTIC(NumReMats , "Number of instructions re-materialized");
57 STATISTIC(NumInflated , "Number of register classes inflated");
60 EnableJoining("join-liveintervals",
61 cl::desc("Coalesce copies (default=true)"),
65 VerifyCoalescing("verify-coalescing",
66 cl::desc("Verify machine instrs before and after register coalescing"),
69 // Temporary option for testing new coalescer algo.
71 NewCoalescer("new-coalescer", cl::Hidden,
72 cl::desc("Use new coalescer algorithm"));
75 class RegisterCoalescer : public MachineFunctionPass,
76 private LiveRangeEdit::Delegate {
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 /// WorkList - Copy instructions yet to be coalesced.
89 SmallVector<MachineInstr*, 8> WorkList;
91 /// ErasedInstrs - Set of instruction pointers that have been erased, and
92 /// that may be present in WorkList.
93 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
95 /// Dead instructions that are about to be deleted.
96 SmallVector<MachineInstr*, 8> DeadDefs;
98 /// Virtual registers to be considered for register class inflation.
99 SmallVector<unsigned, 8> InflateRegs;
101 /// Recursively eliminate dead defs in DeadDefs.
102 void eliminateDeadDefs();
104 /// LiveRangeEdit callback.
105 void LRE_WillEraseInstruction(MachineInstr *MI);
107 /// joinAllIntervals - join compatible live intervals
108 void joinAllIntervals();
110 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
111 /// copies that cannot yet be coalesced into WorkList.
112 void copyCoalesceInMBB(MachineBasicBlock *MBB);
114 /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
115 /// position From. Return true if any progress was made.
116 bool copyCoalesceWorkList(unsigned From = 0);
118 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
119 /// which are the src/dst of the copy instruction CopyMI. This returns
120 /// true if the copy was successfully coalesced away. If it is not
121 /// currently possible to coalesce this interval, but it may be possible if
122 /// other things get coalesced, then it returns true by reference in
124 bool joinCopy(MachineInstr *TheCopy, bool &Again);
126 /// joinIntervals - Attempt to join these two intervals. On failure, this
127 /// returns false. The output "SrcInt" will not have been modified, so we
128 /// can use this information below to update aliases.
129 bool joinIntervals(CoalescerPair &CP);
131 /// Attempt joining two virtual registers. Return true on success.
132 bool joinVirtRegs(CoalescerPair &CP);
134 /// Attempt joining with a reserved physreg.
135 bool joinReservedPhysReg(CoalescerPair &CP);
137 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
138 /// the source value number is defined by a copy from the destination reg
139 /// see if we can merge these two destination reg valno# into a single
140 /// value number, eliminating a copy.
141 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
143 /// hasOtherReachingDefs - Return true if there are definitions of IntB
144 /// other than BValNo val# that can reach uses of AValno val# of IntA.
145 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
146 VNInfo *AValNo, VNInfo *BValNo);
148 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
149 /// If the source value number is defined by a commutable instruction and
150 /// its other operand is coalesced to the copy dest register, see if we
151 /// can transform the copy into a noop by commuting the definition.
152 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
154 /// reMaterializeTrivialDef - If the source of a copy is defined by a
155 /// trivial computation, replace the copy by rematerialize the definition.
156 bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
157 MachineInstr *CopyMI);
159 /// canJoinPhys - Return true if a physreg copy should be joined.
160 bool canJoinPhys(CoalescerPair &CP);
162 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
163 /// update the subregister number if it is not zero. If DstReg is a
164 /// physical register and the existing subregister number of the def / use
165 /// being updated is not zero, make sure to set it to the correct physical
167 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
169 /// eliminateUndefCopy - Handle copies of undef values.
170 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
173 static char ID; // Class identification, replacement for typeinfo
174 RegisterCoalescer() : MachineFunctionPass(ID) {
175 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
178 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
180 virtual void releaseMemory();
182 /// runOnMachineFunction - pass entry point
183 virtual bool runOnMachineFunction(MachineFunction&);
185 /// print - Implement the dump method.
186 virtual void print(raw_ostream &O, const Module* = 0) const;
188 } /// end anonymous namespace
190 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
192 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
193 "Simple Register Coalescing", false, false)
194 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
195 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
196 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
197 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
198 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
199 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
200 "Simple Register Coalescing", false, false)
202 char RegisterCoalescer::ID = 0;
204 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
207 return tri.composeSubRegIndices(a, b);
210 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
211 unsigned &Src, unsigned &Dst,
212 unsigned &SrcSub, unsigned &DstSub) {
214 Dst = MI->getOperand(0).getReg();
215 DstSub = MI->getOperand(0).getSubReg();
216 Src = MI->getOperand(1).getReg();
217 SrcSub = MI->getOperand(1).getSubReg();
218 } else if (MI->isSubregToReg()) {
219 Dst = MI->getOperand(0).getReg();
220 DstSub = compose(tri, MI->getOperand(0).getSubReg(),
221 MI->getOperand(3).getImm());
222 Src = MI->getOperand(2).getReg();
223 SrcSub = MI->getOperand(2).getSubReg();
229 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
233 Flipped = CrossClass = false;
235 unsigned Src, Dst, SrcSub, DstSub;
236 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
238 Partial = SrcSub || DstSub;
240 // If one register is a physreg, it must be Dst.
241 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
242 if (TargetRegisterInfo::isPhysicalRegister(Dst))
245 std::swap(SrcSub, DstSub);
249 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
251 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
252 // Eliminate DstSub on a physreg.
254 Dst = TRI.getSubReg(Dst, DstSub);
255 if (!Dst) return false;
259 // Eliminate SrcSub by picking a corresponding Dst superregister.
261 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
262 if (!Dst) return false;
264 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
268 // Both registers are virtual.
269 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
270 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
272 // Both registers have subreg indices.
273 if (SrcSub && DstSub) {
274 // Copies between different sub-registers are never coalescable.
275 if (Src == Dst && SrcSub != DstSub)
278 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
283 // SrcReg will be merged with a sub-register of DstReg.
285 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
287 // DstReg will be merged with a sub-register of SrcReg.
289 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
291 // This is a straight copy without sub-registers.
292 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
295 // The combined constraint may be impossible to satisfy.
299 // Prefer SrcReg to be a sub-register of DstReg.
300 // FIXME: Coalescer should support subregs symmetrically.
301 if (DstIdx && !SrcIdx) {
303 std::swap(SrcIdx, DstIdx);
307 CrossClass = NewRC != DstRC || NewRC != SrcRC;
309 // Check our invariants
310 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
311 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
312 "Cannot have a physical SubIdx");
318 bool CoalescerPair::flip() {
319 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
321 std::swap(SrcReg, DstReg);
322 std::swap(SrcIdx, DstIdx);
327 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
330 unsigned Src, Dst, SrcSub, DstSub;
331 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
334 // Find the virtual register that is SrcReg.
337 std::swap(SrcSub, DstSub);
338 } else if (Src != SrcReg) {
342 // Now check that Dst matches DstReg.
343 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
344 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
346 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
347 // DstSub could be set for a physreg from INSERT_SUBREG.
349 Dst = TRI.getSubReg(Dst, DstSub);
352 return DstReg == Dst;
353 // This is a partial register copy. Check that the parts match.
354 return TRI.getSubReg(DstReg, SrcSub) == Dst;
356 // DstReg is virtual.
359 // Registers match, do the subregisters line up?
360 return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
364 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
365 AU.setPreservesCFG();
366 AU.addRequired<AliasAnalysis>();
367 AU.addRequired<LiveIntervals>();
368 AU.addPreserved<LiveIntervals>();
369 AU.addRequired<LiveDebugVariables>();
370 AU.addPreserved<LiveDebugVariables>();
371 AU.addPreserved<SlotIndexes>();
372 AU.addRequired<MachineLoopInfo>();
373 AU.addPreserved<MachineLoopInfo>();
374 AU.addPreservedID(MachineDominatorsID);
375 MachineFunctionPass::getAnalysisUsage(AU);
378 void RegisterCoalescer::eliminateDeadDefs() {
379 SmallVector<LiveInterval*, 8> NewRegs;
380 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
383 // Callback from eliminateDeadDefs().
384 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
385 // MI may be in WorkList. Make sure we don't visit it.
386 ErasedInstrs.insert(MI);
389 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
390 /// being the source and IntB being the dest, thus this defines a value number
391 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
392 /// see if we can merge these two pieces of B into a single value number,
393 /// eliminating a copy. For example:
397 /// B1 = A3 <- this copy
399 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
400 /// value number to be replaced with B0 (which simplifies the B liveinterval).
402 /// This returns true if an interval was modified.
404 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
405 MachineInstr *CopyMI) {
406 assert(!CP.isPartial() && "This doesn't work for partial copies.");
407 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
410 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
412 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
413 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
415 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
416 // the example above.
417 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
418 if (BLR == IntB.end()) return false;
419 VNInfo *BValNo = BLR->valno;
421 // Get the location that B is defined at. Two options: either this value has
422 // an unknown definition point or it is defined at CopyIdx. If unknown, we
424 if (BValNo->def != CopyIdx) return false;
426 // AValNo is the value number in A that defines the copy, A3 in the example.
427 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
428 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
429 // The live range might not exist after fun with physreg coalescing.
430 if (ALR == IntA.end()) return false;
431 VNInfo *AValNo = ALR->valno;
433 // If AValNo is defined as a copy from IntB, we can potentially process this.
434 // Get the instruction that defines this value number.
435 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
436 if (!CP.isCoalescable(ACopyMI))
439 // Get the LiveRange in IntB that this value number starts with.
440 LiveInterval::iterator ValLR =
441 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
442 if (ValLR == IntB.end())
445 // Make sure that the end of the live range is inside the same block as
447 MachineInstr *ValLREndInst =
448 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
449 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
452 // Okay, we now know that ValLR ends in the same block that the CopyMI
453 // live-range starts. If there are no intervening live ranges between them in
454 // IntB, we can merge them.
455 if (ValLR+1 != BLR) return false;
457 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
459 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
460 // We are about to delete CopyMI, so need to remove it as the 'instruction
461 // that defines this value #'. Update the valnum with the new defining
463 BValNo->def = FillerStart;
465 // Okay, we can merge them. We need to insert a new liverange:
466 // [ValLR.end, BLR.begin) of either value number, then we merge the
467 // two value numbers.
468 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
470 // Okay, merge "B1" into the same value number as "B0".
471 if (BValNo != ValLR->valno)
472 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
473 DEBUG(dbgs() << " result = " << IntB << '\n');
475 // If the source instruction was killing the source register before the
476 // merge, unset the isKill marker given the live range has been extended.
477 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
479 ValLREndInst->getOperand(UIdx).setIsKill(false);
482 // Rewrite the copy. If the copy instruction was killing the destination
483 // register before the merge, find the last use and trim the live range. That
484 // will also add the isKill marker.
485 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
486 if (ALR->end == CopyIdx)
487 LIS->shrinkToUses(&IntA);
493 /// hasOtherReachingDefs - Return true if there are definitions of IntB
494 /// other than BValNo val# that can reach uses of AValno val# of IntA.
495 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
499 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
501 if (LIS->hasPHIKill(IntA, AValNo))
504 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
506 if (AI->valno != AValNo) continue;
507 LiveInterval::Ranges::iterator BI =
508 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
509 if (BI != IntB.ranges.begin())
511 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
512 if (BI->valno == BValNo)
514 if (BI->start <= AI->start && BI->end > AI->start)
516 if (BI->start > AI->start && BI->start < AI->end)
523 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
524 /// IntA being the source and IntB being the dest, thus this defines a value
525 /// number in IntB. If the source value number (in IntA) is defined by a
526 /// commutable instruction and its other operand is coalesced to the copy dest
527 /// register, see if we can transform the copy into a noop by commuting the
528 /// definition. For example,
530 /// A3 = op A2 B0<kill>
532 /// B1 = A3 <- this copy
534 /// = op A3 <- more uses
538 /// B2 = op B0 A2<kill>
540 /// B1 = B2 <- now an identify copy
542 /// = op B2 <- more uses
544 /// This returns true if an interval was modified.
546 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
547 MachineInstr *CopyMI) {
548 assert (!CP.isPhys());
550 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
553 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
555 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
557 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
558 // the example above.
559 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
560 if (!BValNo || BValNo->def != CopyIdx)
563 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
565 // AValNo is the value number in A that defines the copy, A3 in the example.
566 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
567 assert(AValNo && "COPY source not live");
568 if (AValNo->isPHIDef() || AValNo->isUnused())
570 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
573 if (!DefMI->isCommutable())
575 // If DefMI is a two-address instruction then commuting it will change the
576 // destination register.
577 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
578 assert(DefIdx != -1);
580 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
582 unsigned Op1, Op2, NewDstIdx;
583 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
587 else if (Op2 == UseOpIdx)
592 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
593 unsigned NewReg = NewDstMO.getReg();
594 if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
597 // Make sure there are no other definitions of IntB that would reach the
598 // uses which the new definition can reach.
599 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
602 // If some of the uses of IntA.reg is already coalesced away, return false.
603 // It's not possible to determine whether it's safe to perform the coalescing.
604 for (MachineRegisterInfo::use_nodbg_iterator UI =
605 MRI->use_nodbg_begin(IntA.reg),
606 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
607 MachineInstr *UseMI = &*UI;
608 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
609 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
610 if (ULR == IntA.end() || ULR->valno != AValNo)
612 // If this use is tied to a def, we can't rewrite the register.
613 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
617 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
620 // At this point we have decided that it is legal to do this
621 // transformation. Start by commuting the instruction.
622 MachineBasicBlock *MBB = DefMI->getParent();
623 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
626 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
627 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
628 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
630 if (NewMI != DefMI) {
631 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
632 MachineBasicBlock::iterator Pos = DefMI;
633 MBB->insert(Pos, NewMI);
636 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
637 NewMI->getOperand(OpIdx).setIsKill();
639 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
648 // Update uses of IntA of the specific Val# with IntB.
649 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
650 UE = MRI->use_end(); UI != UE;) {
651 MachineOperand &UseMO = UI.getOperand();
652 MachineInstr *UseMI = &*UI;
654 if (UseMI->isDebugValue()) {
655 // FIXME These don't have an instruction index. Not clear we have enough
656 // info to decide whether to do this replacement or not. For now do it.
657 UseMO.setReg(NewReg);
660 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
661 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
662 if (ULR == IntA.end() || ULR->valno != AValNo)
664 // Kill flags are no longer accurate. They are recomputed after RA.
665 UseMO.setIsKill(false);
666 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
667 UseMO.substPhysReg(NewReg, *TRI);
669 UseMO.setReg(NewReg);
672 if (!UseMI->isCopy())
674 if (UseMI->getOperand(0).getReg() != IntB.reg ||
675 UseMI->getOperand(0).getSubReg())
678 // This copy will become a noop. If it's defining a new val#, merge it into
680 SlotIndex DefIdx = UseIdx.getRegSlot();
681 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
684 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
685 assert(DVNI->def == DefIdx);
686 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
687 ErasedInstrs.insert(UseMI);
688 LIS->RemoveMachineInstrFromMaps(UseMI);
689 UseMI->eraseFromParent();
692 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
694 VNInfo *ValNo = BValNo;
695 ValNo->def = AValNo->def;
696 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
698 if (AI->valno != AValNo) continue;
699 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
701 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
703 IntA.removeValNo(AValNo);
704 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
709 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
710 /// computation, replace the copy by rematerialize the definition.
711 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
713 MachineInstr *CopyMI) {
714 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
715 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
716 assert(SrcLR != SrcInt.end() && "Live range not found!");
717 VNInfo *ValNo = SrcLR->valno;
718 if (ValNo->isPHIDef() || ValNo->isUnused())
720 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
723 assert(DefMI && "Defining instruction disappeared");
724 if (!DefMI->isAsCheapAsAMove())
726 if (!TII->isTriviallyReMaterializable(DefMI, AA))
728 bool SawStore = false;
729 if (!DefMI->isSafeToMove(TII, AA, SawStore))
731 const MCInstrDesc &MCID = DefMI->getDesc();
732 if (MCID.getNumDefs() != 1)
734 if (!DefMI->isImplicitDef()) {
735 // Make sure the copy destination register class fits the instruction
736 // definition register class. The mismatch can happen as a result of earlier
737 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
738 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
739 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
740 if (MRI->getRegClass(DstReg) != RC)
742 } else if (!RC->contains(DstReg))
746 MachineBasicBlock *MBB = CopyMI->getParent();
747 MachineBasicBlock::iterator MII =
748 llvm::next(MachineBasicBlock::iterator(CopyMI));
749 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
750 MachineInstr *NewMI = prior(MII);
752 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
753 // We need to remember these so we can add intervals once we insert
754 // NewMI into SlotIndexes.
755 SmallVector<unsigned, 4> NewMIImplDefs;
756 for (unsigned i = NewMI->getDesc().getNumOperands(),
757 e = NewMI->getNumOperands(); i != e; ++i) {
758 MachineOperand &MO = NewMI->getOperand(i);
760 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
761 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
762 NewMIImplDefs.push_back(MO.getReg());
766 // CopyMI may have implicit operands, transfer them over to the newly
767 // rematerialized instruction. And update implicit def interval valnos.
768 for (unsigned i = CopyMI->getDesc().getNumOperands(),
769 e = CopyMI->getNumOperands(); i != e; ++i) {
770 MachineOperand &MO = CopyMI->getOperand(i);
772 assert(MO.isImplicit() && "No explicit operands after implict operands.");
773 // Discard VReg implicit defs.
774 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
775 NewMI->addOperand(MO);
780 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
782 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
783 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
784 unsigned Reg = NewMIImplDefs[i];
785 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
786 if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
787 LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
790 CopyMI->eraseFromParent();
791 ErasedInstrs.insert(CopyMI);
792 DEBUG(dbgs() << "Remat: " << *NewMI);
795 // The source interval can become smaller because we removed a use.
796 LIS->shrinkToUses(&SrcInt, &DeadDefs);
797 if (!DeadDefs.empty())
803 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
804 /// values, it only removes local variables. When we have a copy like:
806 /// %vreg1 = COPY %vreg2<undef>
808 /// We delete the copy and remove the corresponding value number from %vreg1.
809 /// Any uses of that value number are marked as <undef>.
810 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
811 const CoalescerPair &CP) {
812 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
813 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
814 if (SrcInt->liveAt(Idx))
816 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
817 if (DstInt->liveAt(Idx))
820 // No intervals are live-in to CopyMI - it is undef.
825 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
826 assert(DeadVNI && "No value defined in DstInt");
827 DstInt->removeValNo(DeadVNI);
829 // Find new undef uses.
830 for (MachineRegisterInfo::reg_nodbg_iterator
831 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
833 MachineOperand &MO = I.getOperand();
834 if (MO.isDef() || MO.isUndef())
836 MachineInstr *MI = MO.getParent();
837 SlotIndex Idx = LIS->getInstructionIndex(MI);
838 if (DstInt->liveAt(Idx))
841 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
846 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
847 /// update the subregister number if it is not zero. If DstReg is a
848 /// physical register and the existing subregister number of the def / use
849 /// being updated is not zero, make sure to set it to the correct physical
851 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
854 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
855 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
857 // Update LiveDebugVariables.
858 LDV->renameRegister(SrcReg, DstReg, SubIdx);
860 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
861 MachineInstr *UseMI = I.skipInstruction();) {
862 SmallVector<unsigned,8> Ops;
864 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
866 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
867 // because SrcReg is a sub-register.
868 if (DstInt && !Reads && SubIdx)
869 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
871 // Replace SrcReg with DstReg in all UseMI operands.
872 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
873 MachineOperand &MO = UseMI->getOperand(Ops[i]);
875 // Adjust <undef> flags in case of sub-register joins. We don't want to
876 // turn a full def into a read-modify-write sub-register def and vice
878 if (SubIdx && MO.isDef())
879 MO.setIsUndef(!Reads);
882 MO.substPhysReg(DstReg, *TRI);
884 MO.substVirtReg(DstReg, SubIdx, *TRI);
888 dbgs() << "\t\tupdated: ";
889 if (!UseMI->isDebugValue())
890 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
896 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
897 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
898 /// Always join simple intervals that are defined by a single copy from a
899 /// reserved register. This doesn't increase register pressure, so it is
900 /// always beneficial.
901 if (!RegClassInfo.isReserved(CP.getDstReg())) {
902 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
906 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
907 if (CP.isFlipped() && JoinVInt.containsOneValue())
910 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
914 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
915 /// which are the src/dst of the copy instruction CopyMI. This returns true
916 /// if the copy was successfully coalesced away. If it is not currently
917 /// possible to coalesce this interval, but it may be possible if other
918 /// things get coalesced, then it returns true by reference in 'Again'.
919 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
922 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
924 CoalescerPair CP(*TRI);
925 if (!CP.setRegisters(CopyMI)) {
926 DEBUG(dbgs() << "\tNot coalescable.\n");
930 // Dead code elimination. This really should be handled by MachineDCE, but
931 // sometimes dead copies slip through, and we can't generate invalid live
933 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
934 DEBUG(dbgs() << "\tCopy is dead.\n");
935 DeadDefs.push_back(CopyMI);
941 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
942 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
943 LIS->RemoveMachineInstrFromMaps(CopyMI);
944 CopyMI->eraseFromParent();
945 return false; // Not coalescable.
948 // Coalesced copies are normally removed immediately, but transformations
949 // like removeCopyByCommutingDef() can inadvertently create identity copies.
950 // When that happens, just join the values and remove the copy.
951 if (CP.getSrcReg() == CP.getDstReg()) {
952 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
953 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
954 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
955 if (VNInfo *DefVNI = LRQ.valueDefined()) {
956 VNInfo *ReadVNI = LRQ.valueIn();
957 assert(ReadVNI && "No value before copy and no <undef> flag.");
958 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
959 LI.MergeValueNumberInto(DefVNI, ReadVNI);
960 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
962 LIS->RemoveMachineInstrFromMaps(CopyMI);
963 CopyMI->eraseFromParent();
969 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
970 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
972 if (!canJoinPhys(CP)) {
973 // Before giving up coalescing, if definition of source is defined by
974 // trivial computation, try rematerializing it.
975 if (!CP.isFlipped() &&
976 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
977 CP.getDstReg(), CopyMI))
983 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
985 if (CP.getDstIdx() && CP.getSrcIdx())
986 dbgs() << PrintReg(CP.getDstReg()) << " in "
987 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
988 << PrintReg(CP.getSrcReg()) << " in "
989 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
991 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
992 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
995 // When possible, let DstReg be the larger interval.
996 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
997 LIS->getInterval(CP.getDstReg()).ranges.size())
1001 // Okay, attempt to join these two intervals. On failure, this returns false.
1002 // Otherwise, if one of the intervals being joined is a physreg, this method
1003 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1004 // been modified, so we can use this information below to update aliases.
1005 if (!joinIntervals(CP)) {
1006 // Coalescing failed.
1008 // If definition of source is defined by trivial computation, try
1009 // rematerializing it.
1010 if (!CP.isFlipped() &&
1011 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1012 CP.getDstReg(), CopyMI))
1015 // If we can eliminate the copy without merging the live ranges, do so now.
1016 if (!CP.isPartial() && !CP.isPhys()) {
1017 if (adjustCopiesBackFrom(CP, CopyMI) ||
1018 removeCopyByCommutingDef(CP, CopyMI)) {
1019 LIS->RemoveMachineInstrFromMaps(CopyMI);
1020 CopyMI->eraseFromParent();
1021 DEBUG(dbgs() << "\tTrivial!\n");
1026 // Otherwise, we are unable to join the intervals.
1027 DEBUG(dbgs() << "\tInterference!\n");
1028 Again = true; // May be possible to coalesce later.
1032 // Coalescing to a virtual register that is of a sub-register class of the
1033 // other. Make sure the resulting register is set to the right register class.
1034 if (CP.isCrossClass()) {
1036 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1039 // Removing sub-register copies can ease the register class constraints.
1040 // Make sure we attempt to inflate the register class of DstReg.
1041 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1042 InflateRegs.push_back(CP.getDstReg());
1044 // CopyMI has been erased by joinIntervals at this point. Remove it from
1045 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1046 // to the work list. This keeps ErasedInstrs from growing needlessly.
1047 ErasedInstrs.erase(CopyMI);
1049 // Rewrite all SrcReg operands to DstReg.
1050 // Also update DstReg operands to include DstIdx if it is set.
1052 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1053 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1055 // SrcReg is guaranteed to be the register whose live interval that is
1057 LIS->removeInterval(CP.getSrcReg());
1059 // Update regalloc hint.
1060 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1063 dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1065 dbgs() << LIS->getInterval(CP.getDstReg());
1073 /// Attempt joining with a reserved physreg.
1074 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1075 assert(CP.isPhys() && "Must be a physreg copy");
1076 assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1077 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1078 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1081 assert(CP.isFlipped() && RHS.containsOneValue() &&
1082 "Invalid join with reserved register");
1084 // Optimization for reserved registers like ESP. We can only merge with a
1085 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1086 // The live range of the reserved register will look like a set of dead defs
1087 // - we don't properly track the live range of reserved registers.
1089 // Deny any overlapping intervals. This depends on all the reserved
1090 // register live ranges to look like dead defs.
1091 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1092 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1093 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1097 // Skip any value computations, we are not adding new values to the
1098 // reserved register. Also skip merging the live ranges, the reserved
1099 // register live range doesn't need to be accurate as long as all the
1102 // Delete the identity copy.
1103 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1104 LIS->RemoveMachineInstrFromMaps(CopyMI);
1105 CopyMI->eraseFromParent();
1107 // We don't track kills for reserved registers.
1108 MRI->clearKillFlags(CP.getSrcReg());
1113 //===----------------------------------------------------------------------===//
1114 // Interference checking and interval joining
1115 //===----------------------------------------------------------------------===//
1117 // In the easiest case, the two live ranges being joined are disjoint, and
1118 // there is no interference to consider. It is quite common, though, to have
1119 // overlapping live ranges, and we need to check if the interference can be
1122 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1123 // This means that two SSA values overlap if and only if the def of one value
1124 // is contained in the live range of the other value. As a special case, the
1125 // overlapping values can be defined at the same index.
1127 // The interference from an overlapping def can be resolved in these cases:
1129 // 1. Coalescable copies. The value is defined by a copy that would become an
1130 // identity copy after joining SrcReg and DstReg. The copy instruction will
1131 // be removed, and the value will be merged with the source value.
1133 // There can be several copies back and forth, causing many values to be
1134 // merged into one. We compute a list of ultimate values in the joined live
1135 // range as well as a mappings from the old value numbers.
1137 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1138 // predecessors have a live out value. It doesn't cause real interference,
1139 // and can be merged into the value it overlaps. Like a coalescable copy, it
1140 // can be erased after joining.
1142 // 3. Copy of external value. The overlapping def may be a copy of a value that
1143 // is already in the other register. This is like a coalescable copy, but
1144 // the live range of the source register must be trimmed after erasing the
1145 // copy instruction:
1148 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1150 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1151 // defining one lane at a time:
1153 // %dst:ssub0<def,read-undef> = FOO
1155 // %dst:ssub1<def> = COPY %src
1157 // The live range of %src overlaps the %dst value defined by FOO, but
1158 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1159 // which was undef anyway.
1161 // The value mapping is more complicated in this case. The final live range
1162 // will have different value numbers for both FOO and BAR, but there is no
1163 // simple mapping from old to new values. It may even be necessary to add
1166 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1167 // is live, but never read. This can happen because we don't compute
1168 // individual live ranges per lane.
1172 // %dst:ssub1<def> = COPY %src
1174 // This kind of interference is only resolved locally. If the clobbered
1175 // lane value escapes the block, the join is aborted.
1178 /// Track information about values in a single virtual register about to be
1179 /// joined. Objects of this class are always created in pairs - one for each
1180 /// side of the CoalescerPair.
1184 // Location of this register in the final joined register.
1185 // Either CP.DstIdx or CP.SrcIdx.
1188 // Values that will be present in the final live range.
1189 SmallVectorImpl<VNInfo*> &NewVNInfo;
1191 const CoalescerPair &CP;
1193 SlotIndexes *Indexes;
1194 const TargetRegisterInfo *TRI;
1196 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1197 // This is suitable for passing to LiveInterval::join().
1198 SmallVector<int, 8> Assignments;
1200 // Conflict resolution for overlapping values.
1201 enum ConflictResolution {
1202 // No overlap, simply keep this value.
1205 // Merge this value into OtherVNI and erase the defining instruction.
1206 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1210 // Merge this value into OtherVNI but keep the defining instruction.
1211 // This is for the special case where OtherVNI is defined by the same
1215 // Keep this value, and have it replace OtherVNI where possible. This
1216 // complicates value mapping since OtherVNI maps to two different values
1217 // before and after this def.
1218 // Used when clobbering undefined or dead lanes.
1221 // Unresolved conflict. Visit later when all values have been mapped.
1224 // Unresolvable conflict. Abort the join.
1228 // Per-value info for LI. The lane bit masks are all relative to the final
1229 // joined register, so they can be compared directly between SrcReg and
1232 ConflictResolution Resolution;
1234 // Lanes written by this def, 0 for unanalyzed values.
1235 unsigned WriteLanes;
1237 // Lanes with defined values in this register. Other lanes are undef and
1239 unsigned ValidLanes;
1241 // Value in LI being redefined by this def.
1244 // Value in the other live range that overlaps this def, if any.
1247 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1248 RedefVNI(0), OtherVNI(0) {}
1250 bool isAnalyzed() const { return WriteLanes != 0; }
1253 // One entry per value number in LI.
1254 SmallVector<Val, 8> Vals;
1256 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1257 VNInfo *stripCopies(VNInfo *VNI);
1258 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1259 void computeAssignment(unsigned ValNo, JoinVals &Other);
1262 JoinVals(LiveInterval &li, unsigned subIdx,
1263 SmallVectorImpl<VNInfo*> &newVNInfo,
1264 const CoalescerPair &cp,
1266 const TargetRegisterInfo *tri)
1267 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1268 Indexes(LIS->getSlotIndexes()), TRI(tri),
1269 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1272 /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1273 /// Returns false if any conflicts were impossible to resolve.
1274 bool mapValues(JoinVals &Other);
1276 /// Try to resolve conflicts that require all values to be mapped.
1277 /// Returns false if any conflicts were impossible to resolve.
1278 bool resolveConflicts(JoinVals &Other);
1280 /// Prune the live range of values in Other.LI where they would conflict with
1281 /// CR_Replace values in LI. Collect end points for restoring the live range
1283 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1285 /// Erase any machine instructions that have been coalesced away.
1286 /// Add erased instructions to ErasedInstrs.
1287 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1288 /// the erased instrs.
1289 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1290 SmallVectorImpl<unsigned> &ShrinkRegs);
1292 /// Get the value assignments suitable for passing to LiveInterval::join.
1293 const int *getAssignments() const { return &Assignments[0]; }
1295 } // end anonymous namespace
1297 /// Compute the bitmask of lanes actually written by DefMI.
1298 /// Set Redef if there are any partial register definitions that depend on the
1299 /// previous value of the register.
1300 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1302 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1303 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1305 L |= TRI->getSubRegIndexLaneMask(compose(*TRI, SubIdx, MO->getSubReg()));
1312 /// Find the ultimate value that VNI was copied from.
1313 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1314 while (!VNI->isPHIDef()) {
1315 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1316 assert(MI && "No defining instruction");
1317 if (!MI->isFullCopy())
1319 unsigned Reg = MI->getOperand(1).getReg();
1320 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1322 LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1325 VNI = LRQ.valueIn();
1330 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1331 /// Return a conflict resolution when possible, but leave the hard cases as
1333 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1334 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1335 /// The recursion always goes upwards in the dominator tree, making loops
1337 JoinVals::ConflictResolution
1338 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1339 Val &V = Vals[ValNo];
1340 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1341 VNInfo *VNI = LI.getValNumInfo(ValNo);
1342 if (VNI->isUnused()) {
1347 // Get the instruction defining this value, compute the lanes written.
1348 const MachineInstr *DefMI = 0;
1349 if (VNI->isPHIDef()) {
1350 // Conservatively assume that all lanes in a PHI are valid.
1351 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1353 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1355 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1357 // If this is a read-modify-write instruction, there may be more valid
1358 // lanes than the ones written by this instruction.
1359 // This only covers partial redef operands. DefMI may have normal use
1360 // operands reading the register. They don't contribute valid lanes.
1362 // This adds ssub1 to the set of valid lanes in %src:
1364 // %src:ssub1<def> = FOO
1366 // This leaves only ssub1 valid, making any other lanes undef:
1368 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1370 // The <read-undef> flag on the def operand means that old lane values are
1373 V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1374 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1375 computeAssignment(V.RedefVNI->id, Other);
1376 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1379 // An IMPLICIT_DEF writes undef values.
1380 if (DefMI->isImplicitDef())
1381 V.ValidLanes &= ~V.WriteLanes;
1384 // Find the value in Other that overlaps VNI->def, if any.
1385 LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1387 // It is possible that both values are defined by the same instruction, or
1388 // the values are PHIs defined in the same block. When that happens, the two
1389 // values should be merged into one, but not into any preceding value.
1390 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1391 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1392 DEBUG(dbgs() << "\t\tDouble def: " << VNI->def << '\n');
1393 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1395 // One value stays, the other is merged. Keep the earlier one, or the first
1397 if (OtherVNI->def < VNI->def)
1398 Other.computeAssignment(OtherVNI->id, *this);
1399 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1400 // This is an early-clobber def overlapping a live-in value in the other
1401 // register. Not mergeable.
1402 V.OtherVNI = OtherLRQ.valueIn();
1403 return CR_Impossible;
1405 V.OtherVNI = OtherVNI;
1406 Val &OtherV = Other.Vals[OtherVNI->id];
1407 // Keep this value, check for conflicts when analyzing OtherVNI.
1408 if (!OtherV.isAnalyzed())
1410 // Both sides have been analyzed now. Do they conflict?
1411 if (V.ValidLanes & OtherV.ValidLanes)
1412 // Overlapping lanes can't be resolved now, maybe later.
1413 return CR_Unresolved;
1418 // No simultaneous def. Is Other live at the def?
1419 V.OtherVNI = OtherLRQ.valueIn();
1421 // No overlap, no conflict.
1424 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1426 // We have overlapping values, or possibly a kill of Other.
1427 // Recursively compute assignments up the dominator tree.
1428 Other.computeAssignment(V.OtherVNI->id, *this);
1429 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1431 // Don't attempt resolving PHI values for now.
1432 if (VNI->isPHIDef())
1433 return CR_Impossible;
1435 // Check for simple erasable conflicts.
1436 if (DefMI->isImplicitDef())
1439 // Include the non-conflict where DefMI is a coalescable copy that kills
1440 // OtherVNI. We still want the copy erased and value numbers merged.
1441 if (CP.isCoalescable(DefMI)) {
1442 // Some of the lanes copied from OtherVNI may be undef, making them undef
1444 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1448 // This may not be a real conflict if DefMI simply kills Other and defines
1450 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1453 // Handle the case where VNI and OtherVNI can be proven to be identical:
1455 // %other = COPY %ext
1456 // %this = COPY %ext <-- Erase this copy
1458 if (DefMI->isFullCopy() && !CP.isPartial() &&
1459 stripCopies(VNI) == stripCopies(V.OtherVNI))
1462 // If the lanes written by this instruction were all undef in OtherVNI, it is
1463 // still safe to join the live ranges. This can't be done with a simple value
1464 // mapping, though - OtherVNI will map to multiple values:
1466 // 1 %dst:ssub0 = FOO <-- OtherVNI
1467 // 2 %src = BAR <-- VNI
1468 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1470 // 5 QUUX %src<kill>
1472 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1473 // handles this complex value mapping.
1474 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1477 // FIXME: Identify CR_Replace opportunities where the clobbered lanes are
1479 return CR_Impossible;
1482 /// Compute the value assignment for ValNo in LI.
1483 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1485 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1486 Val &V = Vals[ValNo];
1487 if (V.isAnalyzed()) {
1488 // Recursion should always move up the dominator tree, so ValNo is not
1489 // supposed to reappear before it has been assigned.
1490 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1493 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1496 // Merge this ValNo into OtherVNI.
1497 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1498 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1499 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1500 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1501 << LI.getValNumInfo(ValNo)->def << " into "
1502 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1503 << V.OtherVNI->def << " --> @"
1504 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1507 // This value number needs to go in the final joined live range.
1508 Assignments[ValNo] = NewVNInfo.size();
1509 NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1514 bool JoinVals::mapValues(JoinVals &Other) {
1515 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1516 computeAssignment(i, Other);
1517 if (Vals[i].Resolution == CR_Impossible) {
1518 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1519 << '@' << LI.getValNumInfo(i)->def << '\n');
1526 bool JoinVals::resolveConflicts(JoinVals &Other) {
1527 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1528 assert (Vals[i].Resolution != CR_Impossible && "Unresolvable conflict");
1529 if (Vals[i].Resolution != CR_Unresolved)
1531 // FIXME: Actually resolve dead lane conflicts.
1532 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1533 << '@' << LI.getValNumInfo(i)->def << '\n');
1539 void JoinVals::pruneValues(JoinVals &Other,
1540 SmallVectorImpl<SlotIndex> &EndPoints) {
1541 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1542 if (Vals[i].Resolution != CR_Replace)
1544 SlotIndex Def = LI.getValNumInfo(i)->def;
1545 LIS->pruneValue(&Other.LI, Def, &EndPoints);
1546 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1547 << ": " << Other.LI << '\n');
1551 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1552 SmallVectorImpl<unsigned> &ShrinkRegs) {
1553 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1554 if (Vals[i].Resolution != CR_Erase)
1556 SlotIndex Def = LI.getValNumInfo(i)->def;
1557 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1558 assert(MI && "No instruction to erase");
1560 unsigned Reg = MI->getOperand(1).getReg();
1561 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1562 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1563 ShrinkRegs.push_back(Reg);
1565 ErasedInstrs.insert(MI);
1566 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1567 LIS->RemoveMachineInstrFromMaps(MI);
1568 MI->eraseFromParent();
1572 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1573 SmallVector<VNInfo*, 16> NewVNInfo;
1574 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1575 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1576 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1577 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1579 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1580 << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1583 // First compute NewVNInfo and the simple value mappings.
1584 // Detect impossible conflicts early.
1585 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1588 // Some conflicts can only be resolved after all values have been mapped.
1589 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1592 // All clear, the live ranges can be merged.
1594 // The merging algorithm in LiveInterval::join() can't handle conflicting
1595 // value mappings, so we need to remove any live ranges that overlap a
1596 // CR_Replace resolution. Collect a set of end points that can be used to
1597 // restore the live range after joining.
1598 SmallVector<SlotIndex, 8> EndPoints;
1599 LHSVals.pruneValues(RHSVals, EndPoints);
1600 RHSVals.pruneValues(LHSVals, EndPoints);
1602 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1603 // registers to require trimming.
1604 SmallVector<unsigned, 8> ShrinkRegs;
1605 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1606 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1607 while (!ShrinkRegs.empty())
1608 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1610 // Join RHS into LHS.
1611 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1614 // Kill flags are going to be wrong if the live ranges were overlapping.
1615 // Eventually, we should simply clear all kill flags when computing live
1616 // ranges. They are reinserted after register allocation.
1617 MRI->clearKillFlags(LHS.reg);
1618 MRI->clearKillFlags(RHS.reg);
1620 if (EndPoints.empty())
1623 // Recompute the parts of the live range we had to remove because of
1624 // CR_Replace conflicts.
1625 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
1626 << " points: " << LHS << '\n');
1627 LIS->extendToIndices(&LHS, EndPoints);
1631 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1632 /// compute what the resultant value numbers for each value in the input two
1633 /// ranges will be. This is complicated by copies between the two which can
1634 /// and will commonly cause multiple value numbers to be merged into one.
1636 /// VN is the value number that we're trying to resolve. InstDefiningValue
1637 /// keeps track of the new InstDefiningValue assignment for the result
1638 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1639 /// whether a value in this or other is a copy from the opposite set.
1640 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1641 /// already been assigned.
1643 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1644 /// contains the value number the copy is from.
1646 static unsigned ComputeUltimateVN(VNInfo *VNI,
1647 SmallVector<VNInfo*, 16> &NewVNInfo,
1648 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1649 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1650 SmallVector<int, 16> &ThisValNoAssignments,
1651 SmallVector<int, 16> &OtherValNoAssignments) {
1652 unsigned VN = VNI->id;
1654 // If the VN has already been computed, just return it.
1655 if (ThisValNoAssignments[VN] >= 0)
1656 return ThisValNoAssignments[VN];
1657 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1659 // If this val is not a copy from the other val, then it must be a new value
1660 // number in the destination.
1661 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1662 if (I == ThisFromOther.end()) {
1663 NewVNInfo.push_back(VNI);
1664 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1666 VNInfo *OtherValNo = I->second;
1668 // Otherwise, this *is* a copy from the RHS. If the other side has already
1669 // been computed, return it.
1670 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1671 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1673 // Mark this value number as currently being computed, then ask what the
1674 // ultimate value # of the other value is.
1675 ThisValNoAssignments[VN] = -2;
1676 unsigned UltimateVN =
1677 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1678 OtherValNoAssignments, ThisValNoAssignments);
1679 return ThisValNoAssignments[VN] = UltimateVN;
1683 // Find out if we have something like
1686 // if so, we can pretend this is actually
1689 // which allows us to coalesce A and B.
1690 // VNI is the definition of B. LR is the life range of A that includes
1691 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1692 // This implies that A dominates B.
1693 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1694 const TargetRegisterInfo &tri,
1698 SmallVector<MachineInstr*, 8> &DupCopies) {
1699 // FIXME: This is very conservative. For example, we don't handle
1700 // physical registers.
1702 MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1704 if (!MI || CP.isPartial() || CP.isPhys())
1707 unsigned A = CP.getDstReg();
1708 if (!TargetRegisterInfo::isVirtualRegister(A))
1711 unsigned B = CP.getSrcReg();
1712 if (!TargetRegisterInfo::isVirtualRegister(B))
1715 MachineInstr *OtherMI = li.getInstructionFromIndex(OtherVNI->def);
1719 if (MI->isImplicitDef()) {
1720 DupCopies.push_back(MI);
1723 if (!MI->isFullCopy())
1725 unsigned Src = MI->getOperand(1).getReg();
1726 if (!TargetRegisterInfo::isVirtualRegister(Src))
1728 if (!OtherMI->isFullCopy())
1730 unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1731 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc))
1734 if (Src != OtherSrc)
1737 // If the copies use two different value numbers of X, we cannot merge
1739 LiveInterval &SrcInt = li.getInterval(Src);
1740 // getVNInfoBefore returns NULL for undef copies. In this case, the
1741 // optimization is still safe.
1742 if (SrcInt.getVNInfoBefore(OtherVNI->def) !=
1743 SrcInt.getVNInfoBefore(VNI->def))
1746 DupCopies.push_back(MI);
1751 /// joinIntervals - Attempt to join these two intervals. On failure, this
1753 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1754 // Handle physreg joins separately.
1756 return joinReservedPhysReg(CP);
1759 return joinVirtRegs(CP);
1761 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1762 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1765 // Compute the final value assignment, assuming that the live ranges can be
1767 SmallVector<int, 16> LHSValNoAssignments;
1768 SmallVector<int, 16> RHSValNoAssignments;
1769 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1770 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1771 SmallVector<VNInfo*, 16> NewVNInfo;
1773 SmallVector<MachineInstr*, 8> DupCopies;
1774 SmallVector<MachineInstr*, 8> DeadCopies;
1776 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1777 DEBUG(dbgs() << "\t\tLHS = " << PrintReg(CP.getDstReg(), TRI) << ' ' << LHS
1780 // Loop over the value numbers of the LHS, seeing if any are defined from
1782 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1785 if (VNI->isUnused() || VNI->isPHIDef())
1787 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1788 assert(MI && "Missing def");
1789 if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1792 // Figure out the value # from the RHS.
1793 VNInfo *OtherVNI = RHS.getVNInfoBefore(VNI->def);
1794 // The copy could be to an aliased physreg.
1798 // DstReg is known to be a register in the LHS interval. If the src is
1799 // from the RHS interval, we can use its value #.
1800 if (CP.isCoalescable(MI))
1801 DeadCopies.push_back(MI);
1802 else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1806 LHSValsDefinedFromRHS[VNI] = OtherVNI;
1809 // Loop over the value numbers of the RHS, seeing if any are defined from
1811 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1814 if (VNI->isUnused() || VNI->isPHIDef())
1816 MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1817 assert(MI && "Missing def");
1818 if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1821 // Figure out the value # from the LHS.
1822 VNInfo *OtherVNI = LHS.getVNInfoBefore(VNI->def);
1823 // The copy could be to an aliased physreg.
1827 // DstReg is known to be a register in the RHS interval. If the src is
1828 // from the LHS interval, we can use its value #.
1829 if (CP.isCoalescable(MI))
1830 DeadCopies.push_back(MI);
1831 else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1835 RHSValsDefinedFromLHS[VNI] = OtherVNI;
1838 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1839 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1840 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1842 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1845 unsigned VN = VNI->id;
1846 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1848 ComputeUltimateVN(VNI, NewVNInfo,
1849 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1850 LHSValNoAssignments, RHSValNoAssignments);
1852 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1855 unsigned VN = VNI->id;
1856 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1858 // If this value number isn't a copy from the LHS, it's a new number.
1859 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1860 NewVNInfo.push_back(VNI);
1861 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1865 ComputeUltimateVN(VNI, NewVNInfo,
1866 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1867 RHSValNoAssignments, LHSValNoAssignments);
1870 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1871 // interval lists to see if these intervals are coalescable.
1872 LiveInterval::const_iterator I = LHS.begin();
1873 LiveInterval::const_iterator IE = LHS.end();
1874 LiveInterval::const_iterator J = RHS.begin();
1875 LiveInterval::const_iterator JE = RHS.end();
1877 // Collect interval end points that will no longer be kills.
1878 SmallVector<MachineInstr*, 8> LHSOldKills;
1879 SmallVector<MachineInstr*, 8> RHSOldKills;
1881 // Skip ahead until the first place of potential sharing.
1882 if (I != IE && J != JE) {
1883 if (I->start < J->start) {
1884 I = std::upper_bound(I, IE, J->start);
1885 if (I != LHS.begin()) --I;
1886 } else if (J->start < I->start) {
1887 J = std::upper_bound(J, JE, I->start);
1888 if (J != RHS.begin()) --J;
1892 while (I != IE && J != JE) {
1893 // Determine if these two live ranges overlap.
1894 // If so, check value # info to determine if they are really different.
1895 if (I->end > J->start && J->end > I->start) {
1896 // If the live range overlap will map to the same value number in the
1897 // result liverange, we can still coalesce them. If not, we can't.
1898 if (LHSValNoAssignments[I->valno->id] !=
1899 RHSValNoAssignments[J->valno->id])
1902 // Extended live ranges should no longer be killed.
1903 if (!I->end.isBlock() && I->end < J->end)
1904 if (MachineInstr *MI = LIS->getInstructionFromIndex(I->end))
1905 LHSOldKills.push_back(MI);
1906 if (!J->end.isBlock() && J->end < I->end)
1907 if (MachineInstr *MI = LIS->getInstructionFromIndex(J->end))
1908 RHSOldKills.push_back(MI);
1911 if (I->end < J->end)
1917 // Clear kill flags where live ranges are extended.
1918 while (!LHSOldKills.empty())
1919 LHSOldKills.pop_back_val()->clearRegisterKills(LHS.reg, TRI);
1920 while (!RHSOldKills.empty())
1921 RHSOldKills.pop_back_val()->clearRegisterKills(RHS.reg, TRI);
1923 if (LHSValNoAssignments.empty())
1924 LHSValNoAssignments.push_back(-1);
1925 if (RHSValNoAssignments.empty())
1926 RHSValNoAssignments.push_back(-1);
1928 // Now erase all the redundant copies.
1929 for (unsigned i = 0, e = DeadCopies.size(); i != e; ++i) {
1930 MachineInstr *MI = DeadCopies[i];
1931 if (!ErasedInstrs.insert(MI))
1933 DEBUG(dbgs() << "\t\terased:\t" << LIS->getInstructionIndex(MI)
1935 LIS->RemoveMachineInstrFromMaps(MI);
1936 MI->eraseFromParent();
1939 SmallVector<unsigned, 8> SourceRegisters;
1940 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1941 E = DupCopies.end(); I != E; ++I) {
1942 MachineInstr *MI = *I;
1943 if (!ErasedInstrs.insert(MI))
1946 // If MI is a copy, then we have pretended that the assignment to B in
1949 // was actually a copy from A. Now that we decided to coalesce A and B,
1950 // transform the code into
1952 // In the case of the implicit_def, we just have to remove it.
1953 if (!MI->isImplicitDef()) {
1954 unsigned Src = MI->getOperand(1).getReg();
1955 SourceRegisters.push_back(Src);
1957 LIS->RemoveMachineInstrFromMaps(MI);
1958 MI->eraseFromParent();
1961 // If B = X was the last use of X in a liverange, we have to shrink it now
1962 // that B = X is gone.
1963 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1964 E = SourceRegisters.end(); I != E; ++I) {
1965 LIS->shrinkToUses(&LIS->getInterval(*I));
1968 // If we get here, we know that we can coalesce the live ranges. Ask the
1969 // intervals to coalesce themselves now.
1970 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1976 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1977 // depth of the basic block (the unsigned), and then on the MBB number.
1978 struct DepthMBBCompare {
1979 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1980 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1981 // Deeper loops first
1982 if (LHS.first != RHS.first)
1983 return LHS.first > RHS.first;
1985 // Prefer blocks that are more connected in the CFG. This takes care of
1986 // the most difficult copies first while intervals are short.
1987 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1988 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1992 // As a last resort, sort by block number.
1993 return LHS.second->getNumber() < RHS.second->getNumber();
1998 // Try joining WorkList copies starting from index From.
1999 // Null out any successful joins.
2000 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
2001 assert(From <= WorkList.size() && "Out of range");
2002 bool Progress = false;
2003 for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
2006 // Skip instruction pointers that have already been erased, for example by
2007 // dead code elimination.
2008 if (ErasedInstrs.erase(WorkList[i])) {
2013 bool Success = joinCopy(WorkList[i], Again);
2014 Progress |= Success;
2015 if (Success || !Again)
2022 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2023 DEBUG(dbgs() << MBB->getName() << ":\n");
2025 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2026 // yet, it might invalidate the iterator.
2027 const unsigned PrevSize = WorkList.size();
2028 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2030 if (MII->isCopyLike())
2031 WorkList.push_back(MII);
2033 // Try coalescing the collected copies immediately, and remove the nulls.
2034 // This prevents the WorkList from getting too large since most copies are
2035 // joinable on the first attempt.
2036 if (copyCoalesceWorkList(PrevSize))
2037 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2038 (MachineInstr*)0), WorkList.end());
2041 void RegisterCoalescer::joinAllIntervals() {
2042 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2043 assert(WorkList.empty() && "Old data still around.");
2045 if (Loops->empty()) {
2046 // If there are no loops in the function, join intervals in function order.
2047 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
2049 copyCoalesceInMBB(I);
2051 // Otherwise, join intervals in inner loops before other intervals.
2052 // Unfortunately we can't just iterate over loop hierarchy here because
2053 // there may be more MBB's than BB's. Collect MBB's for sorting.
2055 // Join intervals in the function prolog first. We want to join physical
2056 // registers with virtual registers before the intervals got too long.
2057 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2058 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2059 MachineBasicBlock *MBB = I;
2060 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
2063 // Sort by loop depth.
2064 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2066 // Finally, join intervals in loop nest order.
2067 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2068 copyCoalesceInMBB(MBBs[i].second);
2071 // Joining intervals can allow other intervals to be joined. Iteratively join
2072 // until we make no progress.
2073 while (copyCoalesceWorkList())
2077 void RegisterCoalescer::releaseMemory() {
2078 ErasedInstrs.clear();
2081 InflateRegs.clear();
2084 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2086 MRI = &fn.getRegInfo();
2087 TM = &fn.getTarget();
2088 TRI = TM->getRegisterInfo();
2089 TII = TM->getInstrInfo();
2090 LIS = &getAnalysis<LiveIntervals>();
2091 LDV = &getAnalysis<LiveDebugVariables>();
2092 AA = &getAnalysis<AliasAnalysis>();
2093 Loops = &getAnalysis<MachineLoopInfo>();
2095 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2096 << "********** Function: " << MF->getName() << '\n');
2098 if (VerifyCoalescing)
2099 MF->verify(this, "Before register coalescing");
2101 RegClassInfo.runOnMachineFunction(fn);
2103 // Join (coalesce) intervals if requested.
2107 // After deleting a lot of copies, register classes may be less constrained.
2108 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2110 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2111 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2113 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2114 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2115 unsigned Reg = InflateRegs[i];
2116 if (MRI->reg_nodbg_empty(Reg))
2118 if (MRI->recomputeRegClass(Reg, *TM)) {
2119 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2120 << MRI->getRegClass(Reg)->getName() << '\n');
2127 if (VerifyCoalescing)
2128 MF->verify(this, "After register coalescing");
2132 /// print - Implement the dump method.
2133 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {