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");
58 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
59 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
62 EnableJoining("join-liveintervals",
63 cl::desc("Coalesce copies (default=true)"),
66 // Temporary flag to test critical edge unsplitting.
68 EnableJoinSplits("join-splitedges",
69 cl::desc("Coalesce copies on split edges (default=false)"),
70 cl::init(false), cl::Hidden);
73 VerifyCoalescing("verify-coalescing",
74 cl::desc("Verify machine instrs before and after register coalescing"),
78 class RegisterCoalescer : public MachineFunctionPass,
79 private LiveRangeEdit::Delegate {
81 MachineRegisterInfo* MRI;
82 const TargetMachine* TM;
83 const TargetRegisterInfo* TRI;
84 const TargetInstrInfo* TII;
86 LiveDebugVariables *LDV;
87 const MachineLoopInfo* Loops;
89 RegisterClassInfo RegClassInfo;
91 /// WorkList - Copy instructions yet to be coalesced.
92 SmallVector<MachineInstr*, 8> WorkList;
94 /// ErasedInstrs - Set of instruction pointers that have been erased, and
95 /// that may be present in WorkList.
96 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
98 /// Dead instructions that are about to be deleted.
99 SmallVector<MachineInstr*, 8> DeadDefs;
101 /// Virtual registers to be considered for register class inflation.
102 SmallVector<unsigned, 8> InflateRegs;
104 /// Recursively eliminate dead defs in DeadDefs.
105 void eliminateDeadDefs();
107 /// LiveRangeEdit callback.
108 void LRE_WillEraseInstruction(MachineInstr *MI);
110 /// joinAllIntervals - join compatible live intervals
111 void joinAllIntervals();
113 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
114 /// copies that cannot yet be coalesced into WorkList.
115 void copyCoalesceInMBB(MachineBasicBlock *MBB);
117 /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
118 /// position From. Return true if any progress was made.
119 bool copyCoalesceWorkList(unsigned From = 0);
121 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
122 /// which are the src/dst of the copy instruction CopyMI. This returns
123 /// true if the copy was successfully coalesced away. If it is not
124 /// currently possible to coalesce this interval, but it may be possible if
125 /// other things get coalesced, then it returns true by reference in
127 bool joinCopy(MachineInstr *TheCopy, bool &Again);
129 /// joinIntervals - Attempt to join these two intervals. On failure, this
130 /// returns false. The output "SrcInt" will not have been modified, so we
131 /// can use this information below to update aliases.
132 bool joinIntervals(CoalescerPair &CP);
134 /// Attempt joining two virtual registers. Return true on success.
135 bool joinVirtRegs(CoalescerPair &CP);
137 /// Attempt joining with a reserved physreg.
138 bool joinReservedPhysReg(CoalescerPair &CP);
140 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
141 /// the source value number is defined by a copy from the destination reg
142 /// see if we can merge these two destination reg valno# into a single
143 /// value number, eliminating a copy.
144 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
146 /// hasOtherReachingDefs - Return true if there are definitions of IntB
147 /// other than BValNo val# that can reach uses of AValno val# of IntA.
148 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
149 VNInfo *AValNo, VNInfo *BValNo);
151 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
152 /// If the source value number is defined by a commutable instruction and
153 /// its other operand is coalesced to the copy dest register, see if we
154 /// can transform the copy into a noop by commuting the definition.
155 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
157 /// reMaterializeTrivialDef - If the source of a copy is defined by a
158 /// trivial computation, replace the copy by rematerialize the definition.
159 bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
160 MachineInstr *CopyMI);
162 /// canJoinPhys - Return true if a physreg copy should be joined.
163 bool canJoinPhys(CoalescerPair &CP);
165 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
166 /// update the subregister number if it is not zero. If DstReg is a
167 /// physical register and the existing subregister number of the def / use
168 /// being updated is not zero, make sure to set it to the correct physical
170 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
172 /// eliminateUndefCopy - Handle copies of undef values.
173 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
176 static char ID; // Class identification, replacement for typeinfo
177 RegisterCoalescer() : MachineFunctionPass(ID) {
178 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
181 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
183 virtual void releaseMemory();
185 /// runOnMachineFunction - pass entry point
186 virtual bool runOnMachineFunction(MachineFunction&);
188 /// print - Implement the dump method.
189 virtual void print(raw_ostream &O, const Module* = 0) const;
191 } /// end anonymous namespace
193 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
195 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
196 "Simple Register Coalescing", false, false)
197 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
198 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
199 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
200 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
201 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
202 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
203 "Simple Register Coalescing", false, false)
205 char RegisterCoalescer::ID = 0;
207 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
208 unsigned &Src, unsigned &Dst,
209 unsigned &SrcSub, unsigned &DstSub) {
211 Dst = MI->getOperand(0).getReg();
212 DstSub = MI->getOperand(0).getSubReg();
213 Src = MI->getOperand(1).getReg();
214 SrcSub = MI->getOperand(1).getSubReg();
215 } else if (MI->isSubregToReg()) {
216 Dst = MI->getOperand(0).getReg();
217 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
218 MI->getOperand(3).getImm());
219 Src = MI->getOperand(2).getReg();
220 SrcSub = MI->getOperand(2).getSubReg();
226 // Return true if this block should be vacated by the coalescer to eliminate
227 // branches. The important cases to handle in the coalescer are critical edges
228 // split during phi elimination which contain only copies. Simple blocks that
229 // contain non-branches should also be vacated, but this can be handled by an
230 // earlier pass similar to early if-conversion.
231 static bool isSplitEdge(const MachineBasicBlock *MBB) {
232 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
235 for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end();
237 if (!MII->isCopyLike() || !MII->isUnconditionalBranch())
243 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
247 Flipped = CrossClass = false;
249 unsigned Src, Dst, SrcSub, DstSub;
250 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
252 Partial = SrcSub || DstSub;
254 // If one register is a physreg, it must be Dst.
255 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
256 if (TargetRegisterInfo::isPhysicalRegister(Dst))
259 std::swap(SrcSub, DstSub);
263 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
265 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
266 // Eliminate DstSub on a physreg.
268 Dst = TRI.getSubReg(Dst, DstSub);
269 if (!Dst) return false;
273 // Eliminate SrcSub by picking a corresponding Dst superregister.
275 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
276 if (!Dst) return false;
278 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
282 // Both registers are virtual.
283 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
284 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
286 // Both registers have subreg indices.
287 if (SrcSub && DstSub) {
288 // Copies between different sub-registers are never coalescable.
289 if (Src == Dst && SrcSub != DstSub)
292 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
297 // SrcReg will be merged with a sub-register of DstReg.
299 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
301 // DstReg will be merged with a sub-register of SrcReg.
303 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
305 // This is a straight copy without sub-registers.
306 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
309 // The combined constraint may be impossible to satisfy.
313 // Prefer SrcReg to be a sub-register of DstReg.
314 // FIXME: Coalescer should support subregs symmetrically.
315 if (DstIdx && !SrcIdx) {
317 std::swap(SrcIdx, DstIdx);
321 CrossClass = NewRC != DstRC || NewRC != SrcRC;
323 // Check our invariants
324 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
325 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
326 "Cannot have a physical SubIdx");
332 bool CoalescerPair::flip() {
333 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
335 std::swap(SrcReg, DstReg);
336 std::swap(SrcIdx, DstIdx);
341 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
344 unsigned Src, Dst, SrcSub, DstSub;
345 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
348 // Find the virtual register that is SrcReg.
351 std::swap(SrcSub, DstSub);
352 } else if (Src != SrcReg) {
356 // Now check that Dst matches DstReg.
357 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
358 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
360 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
361 // DstSub could be set for a physreg from INSERT_SUBREG.
363 Dst = TRI.getSubReg(Dst, DstSub);
366 return DstReg == Dst;
367 // This is a partial register copy. Check that the parts match.
368 return TRI.getSubReg(DstReg, SrcSub) == Dst;
370 // DstReg is virtual.
373 // Registers match, do the subregisters line up?
374 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
375 TRI.composeSubRegIndices(DstIdx, DstSub);
379 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
380 AU.setPreservesCFG();
381 AU.addRequired<AliasAnalysis>();
382 AU.addRequired<LiveIntervals>();
383 AU.addPreserved<LiveIntervals>();
384 AU.addRequired<LiveDebugVariables>();
385 AU.addPreserved<LiveDebugVariables>();
386 AU.addPreserved<SlotIndexes>();
387 AU.addRequired<MachineLoopInfo>();
388 AU.addPreserved<MachineLoopInfo>();
389 AU.addPreservedID(MachineDominatorsID);
390 MachineFunctionPass::getAnalysisUsage(AU);
393 void RegisterCoalescer::eliminateDeadDefs() {
394 SmallVector<LiveInterval*, 8> NewRegs;
395 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
398 // Callback from eliminateDeadDefs().
399 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
400 // MI may be in WorkList. Make sure we don't visit it.
401 ErasedInstrs.insert(MI);
404 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
405 /// being the source and IntB being the dest, thus this defines a value number
406 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
407 /// see if we can merge these two pieces of B into a single value number,
408 /// eliminating a copy. For example:
412 /// B1 = A3 <- this copy
414 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
415 /// value number to be replaced with B0 (which simplifies the B liveinterval).
417 /// This returns true if an interval was modified.
419 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
420 MachineInstr *CopyMI) {
421 assert(!CP.isPartial() && "This doesn't work for partial copies.");
422 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
425 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
427 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
428 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
430 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
431 // the example above.
432 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
433 if (BLR == IntB.end()) return false;
434 VNInfo *BValNo = BLR->valno;
436 // Get the location that B is defined at. Two options: either this value has
437 // an unknown definition point or it is defined at CopyIdx. If unknown, we
439 if (BValNo->def != CopyIdx) return false;
441 // AValNo is the value number in A that defines the copy, A3 in the example.
442 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
443 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
444 // The live range might not exist after fun with physreg coalescing.
445 if (ALR == IntA.end()) return false;
446 VNInfo *AValNo = ALR->valno;
448 // If AValNo is defined as a copy from IntB, we can potentially process this.
449 // Get the instruction that defines this value number.
450 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
451 // Don't allow any partial copies, even if isCoalescable() allows them.
452 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
455 // Get the LiveRange in IntB that this value number starts with.
456 LiveInterval::iterator ValLR =
457 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
458 if (ValLR == IntB.end())
461 // Make sure that the end of the live range is inside the same block as
463 MachineInstr *ValLREndInst =
464 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
465 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
468 // Okay, we now know that ValLR ends in the same block that the CopyMI
469 // live-range starts. If there are no intervening live ranges between them in
470 // IntB, we can merge them.
471 if (ValLR+1 != BLR) return false;
473 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
475 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
476 // We are about to delete CopyMI, so need to remove it as the 'instruction
477 // that defines this value #'. Update the valnum with the new defining
479 BValNo->def = FillerStart;
481 // Okay, we can merge them. We need to insert a new liverange:
482 // [ValLR.end, BLR.begin) of either value number, then we merge the
483 // two value numbers.
484 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
486 // Okay, merge "B1" into the same value number as "B0".
487 if (BValNo != ValLR->valno)
488 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
489 DEBUG(dbgs() << " result = " << IntB << '\n');
491 // If the source instruction was killing the source register before the
492 // merge, unset the isKill marker given the live range has been extended.
493 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
495 ValLREndInst->getOperand(UIdx).setIsKill(false);
498 // Rewrite the copy. If the copy instruction was killing the destination
499 // register before the merge, find the last use and trim the live range. That
500 // will also add the isKill marker.
501 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
502 if (ALR->end == CopyIdx)
503 LIS->shrinkToUses(&IntA);
509 /// hasOtherReachingDefs - Return true if there are definitions of IntB
510 /// other than BValNo val# that can reach uses of AValno val# of IntA.
511 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
515 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
517 if (LIS->hasPHIKill(IntA, AValNo))
520 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
522 if (AI->valno != AValNo) continue;
523 LiveInterval::Ranges::iterator BI =
524 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
525 if (BI != IntB.ranges.begin())
527 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
528 if (BI->valno == BValNo)
530 if (BI->start <= AI->start && BI->end > AI->start)
532 if (BI->start > AI->start && BI->start < AI->end)
539 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
540 /// IntA being the source and IntB being the dest, thus this defines a value
541 /// number in IntB. If the source value number (in IntA) is defined by a
542 /// commutable instruction and its other operand is coalesced to the copy dest
543 /// register, see if we can transform the copy into a noop by commuting the
544 /// definition. For example,
546 /// A3 = op A2 B0<kill>
548 /// B1 = A3 <- this copy
550 /// = op A3 <- more uses
554 /// B2 = op B0 A2<kill>
556 /// B1 = B2 <- now an identify copy
558 /// = op B2 <- more uses
560 /// This returns true if an interval was modified.
562 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
563 MachineInstr *CopyMI) {
564 assert (!CP.isPhys());
566 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
569 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
571 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
573 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
574 // the example above.
575 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
576 if (!BValNo || BValNo->def != CopyIdx)
579 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
581 // AValNo is the value number in A that defines the copy, A3 in the example.
582 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
583 assert(AValNo && "COPY source not live");
584 if (AValNo->isPHIDef() || AValNo->isUnused())
586 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
589 if (!DefMI->isCommutable())
591 // If DefMI is a two-address instruction then commuting it will change the
592 // destination register.
593 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
594 assert(DefIdx != -1);
596 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
598 unsigned Op1, Op2, NewDstIdx;
599 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
603 else if (Op2 == UseOpIdx)
608 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
609 unsigned NewReg = NewDstMO.getReg();
610 if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
613 // Make sure there are no other definitions of IntB that would reach the
614 // uses which the new definition can reach.
615 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
618 // If some of the uses of IntA.reg is already coalesced away, return false.
619 // It's not possible to determine whether it's safe to perform the coalescing.
620 for (MachineRegisterInfo::use_nodbg_iterator UI =
621 MRI->use_nodbg_begin(IntA.reg),
622 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
623 MachineInstr *UseMI = &*UI;
624 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
625 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
626 if (ULR == IntA.end() || ULR->valno != AValNo)
628 // If this use is tied to a def, we can't rewrite the register.
629 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
633 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
636 // At this point we have decided that it is legal to do this
637 // transformation. Start by commuting the instruction.
638 MachineBasicBlock *MBB = DefMI->getParent();
639 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
642 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
643 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
644 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
646 if (NewMI != DefMI) {
647 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
648 MachineBasicBlock::iterator Pos = DefMI;
649 MBB->insert(Pos, NewMI);
652 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
653 NewMI->getOperand(OpIdx).setIsKill();
655 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
664 // Update uses of IntA of the specific Val# with IntB.
665 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
666 UE = MRI->use_end(); UI != UE;) {
667 MachineOperand &UseMO = UI.getOperand();
668 MachineInstr *UseMI = &*UI;
670 if (UseMI->isDebugValue()) {
671 // FIXME These don't have an instruction index. Not clear we have enough
672 // info to decide whether to do this replacement or not. For now do it.
673 UseMO.setReg(NewReg);
676 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
677 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
678 if (ULR == IntA.end() || ULR->valno != AValNo)
680 // Kill flags are no longer accurate. They are recomputed after RA.
681 UseMO.setIsKill(false);
682 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
683 UseMO.substPhysReg(NewReg, *TRI);
685 UseMO.setReg(NewReg);
688 if (!UseMI->isCopy())
690 if (UseMI->getOperand(0).getReg() != IntB.reg ||
691 UseMI->getOperand(0).getSubReg())
694 // This copy will become a noop. If it's defining a new val#, merge it into
696 SlotIndex DefIdx = UseIdx.getRegSlot();
697 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
700 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
701 assert(DVNI->def == DefIdx);
702 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
703 ErasedInstrs.insert(UseMI);
704 LIS->RemoveMachineInstrFromMaps(UseMI);
705 UseMI->eraseFromParent();
708 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
710 VNInfo *ValNo = BValNo;
711 ValNo->def = AValNo->def;
712 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
714 if (AI->valno != AValNo) continue;
715 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
717 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
719 IntA.removeValNo(AValNo);
720 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
725 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
726 /// computation, replace the copy by rematerialize the definition.
727 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
729 MachineInstr *CopyMI) {
730 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
731 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
732 assert(SrcLR != SrcInt.end() && "Live range not found!");
733 VNInfo *ValNo = SrcLR->valno;
734 if (ValNo->isPHIDef() || ValNo->isUnused())
736 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
739 assert(DefMI && "Defining instruction disappeared");
740 if (!DefMI->isAsCheapAsAMove())
742 if (!TII->isTriviallyReMaterializable(DefMI, AA))
744 bool SawStore = false;
745 if (!DefMI->isSafeToMove(TII, AA, SawStore))
747 const MCInstrDesc &MCID = DefMI->getDesc();
748 if (MCID.getNumDefs() != 1)
750 if (!DefMI->isImplicitDef()) {
751 // Make sure the copy destination register class fits the instruction
752 // definition register class. The mismatch can happen as a result of earlier
753 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
754 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
755 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
756 if (MRI->getRegClass(DstReg) != RC)
758 } else if (!RC->contains(DstReg))
762 MachineBasicBlock *MBB = CopyMI->getParent();
763 MachineBasicBlock::iterator MII =
764 llvm::next(MachineBasicBlock::iterator(CopyMI));
765 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
766 MachineInstr *NewMI = prior(MII);
768 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
769 // We need to remember these so we can add intervals once we insert
770 // NewMI into SlotIndexes.
771 SmallVector<unsigned, 4> NewMIImplDefs;
772 for (unsigned i = NewMI->getDesc().getNumOperands(),
773 e = NewMI->getNumOperands(); i != e; ++i) {
774 MachineOperand &MO = NewMI->getOperand(i);
776 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
777 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
778 NewMIImplDefs.push_back(MO.getReg());
782 // CopyMI may have implicit operands, transfer them over to the newly
783 // rematerialized instruction. And update implicit def interval valnos.
784 for (unsigned i = CopyMI->getDesc().getNumOperands(),
785 e = CopyMI->getNumOperands(); i != e; ++i) {
786 MachineOperand &MO = CopyMI->getOperand(i);
788 assert(MO.isImplicit() && "No explicit operands after implict operands.");
789 // Discard VReg implicit defs.
790 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
791 NewMI->addOperand(MO);
796 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
798 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
799 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
800 unsigned Reg = NewMIImplDefs[i];
801 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
802 if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
803 LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
806 CopyMI->eraseFromParent();
807 ErasedInstrs.insert(CopyMI);
808 DEBUG(dbgs() << "Remat: " << *NewMI);
811 // The source interval can become smaller because we removed a use.
812 LIS->shrinkToUses(&SrcInt, &DeadDefs);
813 if (!DeadDefs.empty())
819 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
820 /// values, it only removes local variables. When we have a copy like:
822 /// %vreg1 = COPY %vreg2<undef>
824 /// We delete the copy and remove the corresponding value number from %vreg1.
825 /// Any uses of that value number are marked as <undef>.
826 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
827 const CoalescerPair &CP) {
828 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
829 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
830 if (SrcInt->liveAt(Idx))
832 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
833 if (DstInt->liveAt(Idx))
836 // No intervals are live-in to CopyMI - it is undef.
841 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
842 assert(DeadVNI && "No value defined in DstInt");
843 DstInt->removeValNo(DeadVNI);
845 // Find new undef uses.
846 for (MachineRegisterInfo::reg_nodbg_iterator
847 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
849 MachineOperand &MO = I.getOperand();
850 if (MO.isDef() || MO.isUndef())
852 MachineInstr *MI = MO.getParent();
853 SlotIndex Idx = LIS->getInstructionIndex(MI);
854 if (DstInt->liveAt(Idx))
857 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
862 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
863 /// update the subregister number if it is not zero. If DstReg is a
864 /// physical register and the existing subregister number of the def / use
865 /// being updated is not zero, make sure to set it to the correct physical
867 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
870 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
871 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
873 // Update LiveDebugVariables.
874 LDV->renameRegister(SrcReg, DstReg, SubIdx);
876 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
877 MachineInstr *UseMI = I.skipInstruction();) {
878 SmallVector<unsigned,8> Ops;
880 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
882 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
883 // because SrcReg is a sub-register.
884 if (DstInt && !Reads && SubIdx)
885 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
887 // Replace SrcReg with DstReg in all UseMI operands.
888 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
889 MachineOperand &MO = UseMI->getOperand(Ops[i]);
891 // Adjust <undef> flags in case of sub-register joins. We don't want to
892 // turn a full def into a read-modify-write sub-register def and vice
894 if (SubIdx && MO.isDef())
895 MO.setIsUndef(!Reads);
898 MO.substPhysReg(DstReg, *TRI);
900 MO.substVirtReg(DstReg, SubIdx, *TRI);
904 dbgs() << "\t\tupdated: ";
905 if (!UseMI->isDebugValue())
906 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
912 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
913 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
914 /// Always join simple intervals that are defined by a single copy from a
915 /// reserved register. This doesn't increase register pressure, so it is
916 /// always beneficial.
917 if (!MRI->isReserved(CP.getDstReg())) {
918 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
922 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
923 if (CP.isFlipped() && JoinVInt.containsOneValue())
926 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
930 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
931 /// which are the src/dst of the copy instruction CopyMI. This returns true
932 /// if the copy was successfully coalesced away. If it is not currently
933 /// possible to coalesce this interval, but it may be possible if other
934 /// things get coalesced, then it returns true by reference in 'Again'.
935 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
938 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
940 CoalescerPair CP(*TRI);
941 if (!CP.setRegisters(CopyMI)) {
942 DEBUG(dbgs() << "\tNot coalescable.\n");
946 // Dead code elimination. This really should be handled by MachineDCE, but
947 // sometimes dead copies slip through, and we can't generate invalid live
949 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
950 DEBUG(dbgs() << "\tCopy is dead.\n");
951 DeadDefs.push_back(CopyMI);
957 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
958 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
959 LIS->RemoveMachineInstrFromMaps(CopyMI);
960 CopyMI->eraseFromParent();
961 return false; // Not coalescable.
964 // Coalesced copies are normally removed immediately, but transformations
965 // like removeCopyByCommutingDef() can inadvertently create identity copies.
966 // When that happens, just join the values and remove the copy.
967 if (CP.getSrcReg() == CP.getDstReg()) {
968 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
969 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
970 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
971 if (VNInfo *DefVNI = LRQ.valueDefined()) {
972 VNInfo *ReadVNI = LRQ.valueIn();
973 assert(ReadVNI && "No value before copy and no <undef> flag.");
974 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
975 LI.MergeValueNumberInto(DefVNI, ReadVNI);
976 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
978 LIS->RemoveMachineInstrFromMaps(CopyMI);
979 CopyMI->eraseFromParent();
985 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
986 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
988 if (!canJoinPhys(CP)) {
989 // Before giving up coalescing, if definition of source is defined by
990 // trivial computation, try rematerializing it.
991 if (!CP.isFlipped() &&
992 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
993 CP.getDstReg(), CopyMI))
999 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1001 if (CP.getDstIdx() && CP.getSrcIdx())
1002 dbgs() << PrintReg(CP.getDstReg()) << " in "
1003 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1004 << PrintReg(CP.getSrcReg()) << " in "
1005 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1007 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1008 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1011 // When possible, let DstReg be the larger interval.
1012 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1013 LIS->getInterval(CP.getDstReg()).ranges.size())
1017 // Okay, attempt to join these two intervals. On failure, this returns false.
1018 // Otherwise, if one of the intervals being joined is a physreg, this method
1019 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1020 // been modified, so we can use this information below to update aliases.
1021 if (!joinIntervals(CP)) {
1022 // Coalescing failed.
1024 // If definition of source is defined by trivial computation, try
1025 // rematerializing it.
1026 if (!CP.isFlipped() &&
1027 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1028 CP.getDstReg(), CopyMI))
1031 // If we can eliminate the copy without merging the live ranges, do so now.
1032 if (!CP.isPartial() && !CP.isPhys()) {
1033 if (adjustCopiesBackFrom(CP, CopyMI) ||
1034 removeCopyByCommutingDef(CP, CopyMI)) {
1035 LIS->RemoveMachineInstrFromMaps(CopyMI);
1036 CopyMI->eraseFromParent();
1037 DEBUG(dbgs() << "\tTrivial!\n");
1042 // Otherwise, we are unable to join the intervals.
1043 DEBUG(dbgs() << "\tInterference!\n");
1044 Again = true; // May be possible to coalesce later.
1048 // Coalescing to a virtual register that is of a sub-register class of the
1049 // other. Make sure the resulting register is set to the right register class.
1050 if (CP.isCrossClass()) {
1052 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1055 // Removing sub-register copies can ease the register class constraints.
1056 // Make sure we attempt to inflate the register class of DstReg.
1057 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1058 InflateRegs.push_back(CP.getDstReg());
1060 // CopyMI has been erased by joinIntervals at this point. Remove it from
1061 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1062 // to the work list. This keeps ErasedInstrs from growing needlessly.
1063 ErasedInstrs.erase(CopyMI);
1065 // Rewrite all SrcReg operands to DstReg.
1066 // Also update DstReg operands to include DstIdx if it is set.
1068 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1069 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1071 // SrcReg is guaranteed to be the register whose live interval that is
1073 LIS->removeInterval(CP.getSrcReg());
1075 // Update regalloc hint.
1076 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1079 dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1081 dbgs() << LIS->getInterval(CP.getDstReg());
1089 /// Attempt joining with a reserved physreg.
1090 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1091 assert(CP.isPhys() && "Must be a physreg copy");
1092 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1093 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1094 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1097 assert(CP.isFlipped() && RHS.containsOneValue() &&
1098 "Invalid join with reserved register");
1100 // Optimization for reserved registers like ESP. We can only merge with a
1101 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1102 // The live range of the reserved register will look like a set of dead defs
1103 // - we don't properly track the live range of reserved registers.
1105 // Deny any overlapping intervals. This depends on all the reserved
1106 // register live ranges to look like dead defs.
1107 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1108 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1109 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1113 // Skip any value computations, we are not adding new values to the
1114 // reserved register. Also skip merging the live ranges, the reserved
1115 // register live range doesn't need to be accurate as long as all the
1118 // Delete the identity copy.
1119 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1120 LIS->RemoveMachineInstrFromMaps(CopyMI);
1121 CopyMI->eraseFromParent();
1123 // We don't track kills for reserved registers.
1124 MRI->clearKillFlags(CP.getSrcReg());
1129 //===----------------------------------------------------------------------===//
1130 // Interference checking and interval joining
1131 //===----------------------------------------------------------------------===//
1133 // In the easiest case, the two live ranges being joined are disjoint, and
1134 // there is no interference to consider. It is quite common, though, to have
1135 // overlapping live ranges, and we need to check if the interference can be
1138 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1139 // This means that two SSA values overlap if and only if the def of one value
1140 // is contained in the live range of the other value. As a special case, the
1141 // overlapping values can be defined at the same index.
1143 // The interference from an overlapping def can be resolved in these cases:
1145 // 1. Coalescable copies. The value is defined by a copy that would become an
1146 // identity copy after joining SrcReg and DstReg. The copy instruction will
1147 // be removed, and the value will be merged with the source value.
1149 // There can be several copies back and forth, causing many values to be
1150 // merged into one. We compute a list of ultimate values in the joined live
1151 // range as well as a mappings from the old value numbers.
1153 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1154 // predecessors have a live out value. It doesn't cause real interference,
1155 // and can be merged into the value it overlaps. Like a coalescable copy, it
1156 // can be erased after joining.
1158 // 3. Copy of external value. The overlapping def may be a copy of a value that
1159 // is already in the other register. This is like a coalescable copy, but
1160 // the live range of the source register must be trimmed after erasing the
1161 // copy instruction:
1164 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1166 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1167 // defining one lane at a time:
1169 // %dst:ssub0<def,read-undef> = FOO
1171 // %dst:ssub1<def> = COPY %src
1173 // The live range of %src overlaps the %dst value defined by FOO, but
1174 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1175 // which was undef anyway.
1177 // The value mapping is more complicated in this case. The final live range
1178 // will have different value numbers for both FOO and BAR, but there is no
1179 // simple mapping from old to new values. It may even be necessary to add
1182 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1183 // is live, but never read. This can happen because we don't compute
1184 // individual live ranges per lane.
1188 // %dst:ssub1<def> = COPY %src
1190 // This kind of interference is only resolved locally. If the clobbered
1191 // lane value escapes the block, the join is aborted.
1194 /// Track information about values in a single virtual register about to be
1195 /// joined. Objects of this class are always created in pairs - one for each
1196 /// side of the CoalescerPair.
1200 // Location of this register in the final joined register.
1201 // Either CP.DstIdx or CP.SrcIdx.
1204 // Values that will be present in the final live range.
1205 SmallVectorImpl<VNInfo*> &NewVNInfo;
1207 const CoalescerPair &CP;
1209 SlotIndexes *Indexes;
1210 const TargetRegisterInfo *TRI;
1212 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1213 // This is suitable for passing to LiveInterval::join().
1214 SmallVector<int, 8> Assignments;
1216 // Conflict resolution for overlapping values.
1217 enum ConflictResolution {
1218 // No overlap, simply keep this value.
1221 // Merge this value into OtherVNI and erase the defining instruction.
1222 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1226 // Merge this value into OtherVNI but keep the defining instruction.
1227 // This is for the special case where OtherVNI is defined by the same
1231 // Keep this value, and have it replace OtherVNI where possible. This
1232 // complicates value mapping since OtherVNI maps to two different values
1233 // before and after this def.
1234 // Used when clobbering undefined or dead lanes.
1237 // Unresolved conflict. Visit later when all values have been mapped.
1240 // Unresolvable conflict. Abort the join.
1244 // Per-value info for LI. The lane bit masks are all relative to the final
1245 // joined register, so they can be compared directly between SrcReg and
1248 ConflictResolution Resolution;
1250 // Lanes written by this def, 0 for unanalyzed values.
1251 unsigned WriteLanes;
1253 // Lanes with defined values in this register. Other lanes are undef and
1255 unsigned ValidLanes;
1257 // Value in LI being redefined by this def.
1260 // Value in the other live range that overlaps this def, if any.
1263 // Is this value an IMPLICIT_DEF?
1266 // True when the live range of this value will be pruned because of an
1267 // overlapping CR_Replace value in the other live range.
1270 // True once Pruned above has been computed.
1271 bool PrunedComputed;
1273 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1274 RedefVNI(0), OtherVNI(0), IsImplicitDef(false), Pruned(false),
1275 PrunedComputed(false) {}
1277 bool isAnalyzed() const { return WriteLanes != 0; }
1280 // One entry per value number in LI.
1281 SmallVector<Val, 8> Vals;
1283 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1284 VNInfo *stripCopies(VNInfo *VNI);
1285 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1286 void computeAssignment(unsigned ValNo, JoinVals &Other);
1287 bool taintExtent(unsigned, unsigned, JoinVals&,
1288 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1289 bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1290 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1293 JoinVals(LiveInterval &li, unsigned subIdx,
1294 SmallVectorImpl<VNInfo*> &newVNInfo,
1295 const CoalescerPair &cp,
1297 const TargetRegisterInfo *tri)
1298 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1299 Indexes(LIS->getSlotIndexes()), TRI(tri),
1300 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1303 /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1304 /// Returns false if any conflicts were impossible to resolve.
1305 bool mapValues(JoinVals &Other);
1307 /// Try to resolve conflicts that require all values to be mapped.
1308 /// Returns false if any conflicts were impossible to resolve.
1309 bool resolveConflicts(JoinVals &Other);
1311 /// Prune the live range of values in Other.LI where they would conflict with
1312 /// CR_Replace values in LI. Collect end points for restoring the live range
1314 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1316 /// Erase any machine instructions that have been coalesced away.
1317 /// Add erased instructions to ErasedInstrs.
1318 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1319 /// the erased instrs.
1320 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1321 SmallVectorImpl<unsigned> &ShrinkRegs);
1323 /// Get the value assignments suitable for passing to LiveInterval::join.
1324 const int *getAssignments() const { return Assignments.data(); }
1326 } // end anonymous namespace
1328 /// Compute the bitmask of lanes actually written by DefMI.
1329 /// Set Redef if there are any partial register definitions that depend on the
1330 /// previous value of the register.
1331 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1333 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1334 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1336 L |= TRI->getSubRegIndexLaneMask(
1337 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1344 /// Find the ultimate value that VNI was copied from.
1345 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1346 while (!VNI->isPHIDef()) {
1347 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1348 assert(MI && "No defining instruction");
1349 if (!MI->isFullCopy())
1351 unsigned Reg = MI->getOperand(1).getReg();
1352 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1354 LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1357 VNI = LRQ.valueIn();
1362 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1363 /// Return a conflict resolution when possible, but leave the hard cases as
1365 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1366 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1367 /// The recursion always goes upwards in the dominator tree, making loops
1369 JoinVals::ConflictResolution
1370 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1371 Val &V = Vals[ValNo];
1372 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1373 VNInfo *VNI = LI.getValNumInfo(ValNo);
1374 if (VNI->isUnused()) {
1379 // Get the instruction defining this value, compute the lanes written.
1380 const MachineInstr *DefMI = 0;
1381 if (VNI->isPHIDef()) {
1382 // Conservatively assume that all lanes in a PHI are valid.
1383 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1385 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1387 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1389 // If this is a read-modify-write instruction, there may be more valid
1390 // lanes than the ones written by this instruction.
1391 // This only covers partial redef operands. DefMI may have normal use
1392 // operands reading the register. They don't contribute valid lanes.
1394 // This adds ssub1 to the set of valid lanes in %src:
1396 // %src:ssub1<def> = FOO
1398 // This leaves only ssub1 valid, making any other lanes undef:
1400 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1402 // The <read-undef> flag on the def operand means that old lane values are
1405 V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1406 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1407 computeAssignment(V.RedefVNI->id, Other);
1408 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1411 // An IMPLICIT_DEF writes undef values.
1412 if (DefMI->isImplicitDef()) {
1413 V.IsImplicitDef = true;
1414 V.ValidLanes &= ~V.WriteLanes;
1418 // Find the value in Other that overlaps VNI->def, if any.
1419 LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1421 // It is possible that both values are defined by the same instruction, or
1422 // the values are PHIs defined in the same block. When that happens, the two
1423 // values should be merged into one, but not into any preceding value.
1424 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1425 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1426 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1428 // One value stays, the other is merged. Keep the earlier one, or the first
1430 if (OtherVNI->def < VNI->def)
1431 Other.computeAssignment(OtherVNI->id, *this);
1432 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1433 // This is an early-clobber def overlapping a live-in value in the other
1434 // register. Not mergeable.
1435 V.OtherVNI = OtherLRQ.valueIn();
1436 return CR_Impossible;
1438 V.OtherVNI = OtherVNI;
1439 Val &OtherV = Other.Vals[OtherVNI->id];
1440 // Keep this value, check for conflicts when analyzing OtherVNI.
1441 if (!OtherV.isAnalyzed())
1443 // Both sides have been analyzed now.
1444 // Allow overlapping PHI values. Any real interference would show up in a
1445 // predecessor, the PHI itself can't introduce any conflicts.
1446 if (VNI->isPHIDef())
1448 if (V.ValidLanes & OtherV.ValidLanes)
1449 // Overlapping lanes can't be resolved.
1450 return CR_Impossible;
1455 // No simultaneous def. Is Other live at the def?
1456 V.OtherVNI = OtherLRQ.valueIn();
1458 // No overlap, no conflict.
1461 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1463 // We have overlapping values, or possibly a kill of Other.
1464 // Recursively compute assignments up the dominator tree.
1465 Other.computeAssignment(V.OtherVNI->id, *this);
1466 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1468 // Allow overlapping PHI values. Any real interference would show up in a
1469 // predecessor, the PHI itself can't introduce any conflicts.
1470 if (VNI->isPHIDef())
1473 // Check for simple erasable conflicts.
1474 if (DefMI->isImplicitDef())
1477 // Include the non-conflict where DefMI is a coalescable copy that kills
1478 // OtherVNI. We still want the copy erased and value numbers merged.
1479 if (CP.isCoalescable(DefMI)) {
1480 // Some of the lanes copied from OtherVNI may be undef, making them undef
1482 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1486 // This may not be a real conflict if DefMI simply kills Other and defines
1488 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1491 // Handle the case where VNI and OtherVNI can be proven to be identical:
1493 // %other = COPY %ext
1494 // %this = COPY %ext <-- Erase this copy
1496 if (DefMI->isFullCopy() && !CP.isPartial() &&
1497 stripCopies(VNI) == stripCopies(V.OtherVNI))
1500 // If the lanes written by this instruction were all undef in OtherVNI, it is
1501 // still safe to join the live ranges. This can't be done with a simple value
1502 // mapping, though - OtherVNI will map to multiple values:
1504 // 1 %dst:ssub0 = FOO <-- OtherVNI
1505 // 2 %src = BAR <-- VNI
1506 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1508 // 5 QUUX %src<kill>
1510 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1511 // handles this complex value mapping.
1512 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1515 // If the other live range is killed by DefMI and the live ranges are still
1516 // overlapping, it must be because we're looking at an early clobber def:
1518 // %dst<def,early-clobber> = ASM %src<kill>
1520 // In this case, it is illegal to merge the two live ranges since the early
1521 // clobber def would clobber %src before it was read.
1522 if (OtherLRQ.isKill()) {
1523 // This case where the def doesn't overlap the kill is handled above.
1524 assert(VNI->def.isEarlyClobber() &&
1525 "Only early clobber defs can overlap a kill");
1526 return CR_Impossible;
1529 // VNI is clobbering live lanes in OtherVNI, but there is still the
1530 // possibility that no instructions actually read the clobbered lanes.
1531 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1532 // Otherwise Other.LI wouldn't be live here.
1533 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1534 return CR_Impossible;
1536 // We need to verify that no instructions are reading the clobbered lanes. To
1537 // save compile time, we'll only check that locally. Don't allow the tainted
1538 // value to escape the basic block.
1539 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1540 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1541 return CR_Impossible;
1543 // There are still some things that could go wrong besides clobbered lanes
1544 // being read, for example OtherVNI may be only partially redefined in MBB,
1545 // and some clobbered lanes could escape the block. Save this analysis for
1546 // resolveConflicts() when all values have been mapped. We need to know
1547 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1548 // that now - the recursive analyzeValue() calls must go upwards in the
1550 return CR_Unresolved;
1553 /// Compute the value assignment for ValNo in LI.
1554 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1556 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1557 Val &V = Vals[ValNo];
1558 if (V.isAnalyzed()) {
1559 // Recursion should always move up the dominator tree, so ValNo is not
1560 // supposed to reappear before it has been assigned.
1561 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1564 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1567 // Merge this ValNo into OtherVNI.
1568 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1569 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1570 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1571 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1572 << LI.getValNumInfo(ValNo)->def << " into "
1573 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1574 << V.OtherVNI->def << " --> @"
1575 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1579 // The other value is going to be pruned if this join is successful.
1580 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1581 Other.Vals[V.OtherVNI->id].Pruned = true;
1584 // This value number needs to go in the final joined live range.
1585 Assignments[ValNo] = NewVNInfo.size();
1586 NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1591 bool JoinVals::mapValues(JoinVals &Other) {
1592 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1593 computeAssignment(i, Other);
1594 if (Vals[i].Resolution == CR_Impossible) {
1595 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1596 << '@' << LI.getValNumInfo(i)->def << '\n');
1603 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1604 /// the extent of the tainted lanes in the block.
1606 /// Multiple values in Other.LI can be affected since partial redefinitions can
1607 /// preserve previously tainted lanes.
1609 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1610 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1611 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1612 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1614 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1615 /// entry to TaintedVals.
1617 /// Returns false if the tainted lanes extend beyond the basic block.
1619 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1620 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1621 VNInfo *VNI = LI.getValNumInfo(ValNo);
1622 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1623 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1625 // Scan Other.LI from VNI.def to MBBEnd.
1626 LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1627 assert(OtherI != Other.LI.end() && "No conflict?");
1629 // OtherI is pointing to a tainted value. Abort the join if the tainted
1630 // lanes escape the block.
1631 SlotIndex End = OtherI->end;
1632 if (End >= MBBEnd) {
1633 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1634 << OtherI->valno->id << '@' << OtherI->start << '\n');
1637 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1638 << OtherI->valno->id << '@' << OtherI->start
1639 << " to " << End << '\n');
1640 // A dead def is not a problem.
1643 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1645 // Check for another def in the MBB.
1646 if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1649 // Lanes written by the new def are no longer tainted.
1650 const Val &OV = Other.Vals[OtherI->valno->id];
1651 TaintedLanes &= ~OV.WriteLanes;
1654 } while (TaintedLanes);
1658 /// Return true if MI uses any of the given Lanes from Reg.
1659 /// This does not include partial redefinitions of Reg.
1660 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1662 if (MI->isDebugValue())
1664 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1665 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1667 if (!MO->readsReg())
1669 if (Lanes & TRI->getSubRegIndexLaneMask(
1670 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
1676 bool JoinVals::resolveConflicts(JoinVals &Other) {
1677 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1679 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1680 if (V.Resolution != CR_Unresolved)
1682 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1683 << '@' << LI.getValNumInfo(i)->def << '\n');
1685 assert(V.OtherVNI && "Inconsistent conflict resolution.");
1686 VNInfo *VNI = LI.getValNumInfo(i);
1687 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1689 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1690 // join, those lanes will be tainted with a wrong value. Get the extent of
1691 // the tainted lanes.
1692 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1693 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1694 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1695 // Tainted lanes would extend beyond the basic block.
1698 assert(!TaintExtent.empty() && "There should be at least one conflict.");
1700 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1701 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1702 MachineBasicBlock::iterator MI = MBB->begin();
1703 if (!VNI->isPHIDef()) {
1704 MI = Indexes->getInstructionFromIndex(VNI->def);
1705 // No need to check the instruction defining VNI for reads.
1708 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1709 "Interference ends on VNI->def. Should have been handled earlier");
1710 MachineInstr *LastMI =
1711 Indexes->getInstructionFromIndex(TaintExtent.front().first);
1712 assert(LastMI && "Range must end at a proper instruction");
1713 unsigned TaintNum = 0;
1715 assert(MI != MBB->end() && "Bad LastMI");
1716 if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1717 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1720 // LastMI is the last instruction to use the current value.
1721 if (&*MI == LastMI) {
1722 if (++TaintNum == TaintExtent.size())
1724 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1725 assert(LastMI && "Range must end at a proper instruction");
1726 TaintedLanes = TaintExtent[TaintNum].second;
1731 // The tainted lanes are unused.
1732 V.Resolution = CR_Replace;
1738 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1742 // %src = COPY %dst <-- This value to be pruned.
1743 // %dst = COPY %src <-- This value is a copy of a pruned value.
1745 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1746 Val &V = Vals[ValNo];
1747 if (V.Pruned || V.PrunedComputed)
1750 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1753 // Follow copies up the dominator tree and check if any intermediate value
1755 V.PrunedComputed = true;
1756 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1760 void JoinVals::pruneValues(JoinVals &Other,
1761 SmallVectorImpl<SlotIndex> &EndPoints) {
1762 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1763 SlotIndex Def = LI.getValNumInfo(i)->def;
1764 switch (Vals[i].Resolution) {
1768 // This value takes precedence over the value in Other.LI.
1769 LIS->pruneValue(&Other.LI, Def, &EndPoints);
1770 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
1771 // instructions are only inserted to provide a live-out value for PHI
1772 // predecessors, so the instruction should simply go away once its value
1773 // has been replaced.
1774 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
1775 bool EraseImpDef = OtherV.IsImplicitDef && OtherV.Resolution == CR_Keep;
1776 if (!Def.isBlock()) {
1777 // Remove <def,read-undef> flags. This def is now a partial redef.
1778 // Also remove <def,dead> flags since the joined live range will
1779 // continue past this instruction.
1780 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
1782 if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
1783 MO->setIsUndef(EraseImpDef);
1784 MO->setIsDead(false);
1786 // This value will reach instructions below, but we need to make sure
1787 // the live range also reaches the instruction at Def.
1789 EndPoints.push_back(Def);
1791 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1792 << ": " << Other.LI << '\n');
1797 if (isPrunedValue(i, Other)) {
1798 // This value is ultimately a copy of a pruned value in LI or Other.LI.
1799 // We can no longer trust the value mapping computed by
1800 // computeAssignment(), the value that was originally copied could have
1802 LIS->pruneValue(&LI, Def, &EndPoints);
1803 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1804 << Def << ": " << LI << '\n');
1809 llvm_unreachable("Unresolved conflicts");
1814 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1815 SmallVectorImpl<unsigned> &ShrinkRegs) {
1816 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1817 // Get the def location before markUnused() below invalidates it.
1818 SlotIndex Def = LI.getValNumInfo(i)->def;
1819 switch (Vals[i].Resolution) {
1821 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
1822 // longer. The IMPLICIT_DEF instructions are only inserted by
1823 // PHIElimination to guarantee that all PHI predecessors have a value.
1824 if (!Vals[i].IsImplicitDef || !Vals[i].Pruned)
1826 // Remove value number i from LI. Note that this VNInfo is still present
1827 // in NewVNInfo, so it will appear as an unused value number in the final
1829 LI.getValNumInfo(i)->markUnused();
1830 LI.removeValNo(LI.getValNumInfo(i));
1831 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
1835 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1836 assert(MI && "No instruction to erase");
1838 unsigned Reg = MI->getOperand(1).getReg();
1839 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1840 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1841 ShrinkRegs.push_back(Reg);
1843 ErasedInstrs.insert(MI);
1844 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1845 LIS->RemoveMachineInstrFromMaps(MI);
1846 MI->eraseFromParent();
1855 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1856 SmallVector<VNInfo*, 16> NewVNInfo;
1857 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1858 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1859 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1860 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1862 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1863 << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1866 // First compute NewVNInfo and the simple value mappings.
1867 // Detect impossible conflicts early.
1868 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1871 // Some conflicts can only be resolved after all values have been mapped.
1872 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1875 // All clear, the live ranges can be merged.
1877 // The merging algorithm in LiveInterval::join() can't handle conflicting
1878 // value mappings, so we need to remove any live ranges that overlap a
1879 // CR_Replace resolution. Collect a set of end points that can be used to
1880 // restore the live range after joining.
1881 SmallVector<SlotIndex, 8> EndPoints;
1882 LHSVals.pruneValues(RHSVals, EndPoints);
1883 RHSVals.pruneValues(LHSVals, EndPoints);
1885 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1886 // registers to require trimming.
1887 SmallVector<unsigned, 8> ShrinkRegs;
1888 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1889 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1890 while (!ShrinkRegs.empty())
1891 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1893 // Join RHS into LHS.
1894 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1897 // Kill flags are going to be wrong if the live ranges were overlapping.
1898 // Eventually, we should simply clear all kill flags when computing live
1899 // ranges. They are reinserted after register allocation.
1900 MRI->clearKillFlags(LHS.reg);
1901 MRI->clearKillFlags(RHS.reg);
1903 if (EndPoints.empty())
1906 // Recompute the parts of the live range we had to remove because of
1907 // CR_Replace conflicts.
1908 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
1909 << " points: " << LHS << '\n');
1910 LIS->extendToIndices(&LHS, EndPoints);
1914 /// joinIntervals - Attempt to join these two intervals. On failure, this
1916 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1917 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
1921 // Information concerning MBB coalescing priority.
1922 struct MBBPriorityInfo {
1923 MachineBasicBlock *MBB;
1927 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
1928 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
1931 // MBBPriorityCompare - Comparison predicate that sorts first based on the
1932 // loop depth of the basic block (the unsigned), and then on the MBB number.
1933 struct MBBPriorityCompare {
1934 bool operator()(const MBBPriorityInfo &LHS,
1935 const MBBPriorityInfo &RHS) const {
1936 // Deeper loops first
1937 if (LHS.Depth != RHS.Depth)
1938 return LHS.Depth > RHS.Depth;
1940 // Try to unsplit critical edges next.
1941 if (EnableJoinSplits && LHS.IsSplit != RHS.IsSplit)
1944 // Prefer blocks that are more connected in the CFG. This takes care of
1945 // the most difficult copies first while intervals are short.
1946 unsigned cl = LHS.MBB->pred_size() + LHS.MBB->succ_size();
1947 unsigned cr = RHS.MBB->pred_size() + RHS.MBB->succ_size();
1951 // As a last resort, sort by block number.
1952 return LHS.MBB->getNumber() < RHS.MBB->getNumber();
1957 // Try joining WorkList copies starting from index From.
1958 // Null out any successful joins.
1959 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1960 assert(From <= WorkList.size() && "Out of range");
1961 bool Progress = false;
1962 for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1965 // Skip instruction pointers that have already been erased, for example by
1966 // dead code elimination.
1967 if (ErasedInstrs.erase(WorkList[i])) {
1972 bool Success = joinCopy(WorkList[i], Again);
1973 Progress |= Success;
1974 if (Success || !Again)
1981 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1982 DEBUG(dbgs() << MBB->getName() << ":\n");
1984 // Collect all copy-like instructions in MBB. Don't start coalescing anything
1985 // yet, it might invalidate the iterator.
1986 const unsigned PrevSize = WorkList.size();
1987 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1989 if (MII->isCopyLike())
1990 WorkList.push_back(MII);
1992 // Try coalescing the collected copies immediately, and remove the nulls.
1993 // This prevents the WorkList from getting too large since most copies are
1994 // joinable on the first attempt.
1995 if (copyCoalesceWorkList(PrevSize))
1996 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
1997 (MachineInstr*)0), WorkList.end());
2000 void RegisterCoalescer::joinAllIntervals() {
2001 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2002 assert(WorkList.empty() && "Old data still around.");
2004 std::vector<MBBPriorityInfo> MBBs;
2005 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2006 MachineBasicBlock *MBB = I;
2007 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2010 std::sort(MBBs.begin(), MBBs.end(), MBBPriorityCompare());
2012 // Coalesce intervals in MBB priority order.
2013 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2014 copyCoalesceInMBB(MBBs[i].MBB);
2016 // Joining intervals can allow other intervals to be joined. Iteratively join
2017 // until we make no progress.
2018 while (copyCoalesceWorkList())
2022 void RegisterCoalescer::releaseMemory() {
2023 ErasedInstrs.clear();
2026 InflateRegs.clear();
2029 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2031 MRI = &fn.getRegInfo();
2032 TM = &fn.getTarget();
2033 TRI = TM->getRegisterInfo();
2034 TII = TM->getInstrInfo();
2035 LIS = &getAnalysis<LiveIntervals>();
2036 LDV = &getAnalysis<LiveDebugVariables>();
2037 AA = &getAnalysis<AliasAnalysis>();
2038 Loops = &getAnalysis<MachineLoopInfo>();
2040 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2041 << "********** Function: " << MF->getName() << '\n');
2043 if (VerifyCoalescing)
2044 MF->verify(this, "Before register coalescing");
2046 RegClassInfo.runOnMachineFunction(fn);
2048 // Join (coalesce) intervals if requested.
2052 // After deleting a lot of copies, register classes may be less constrained.
2053 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2055 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2056 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2058 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2059 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2060 unsigned Reg = InflateRegs[i];
2061 if (MRI->reg_nodbg_empty(Reg))
2063 if (MRI->recomputeRegClass(Reg, *TM)) {
2064 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2065 << MRI->getRegClass(Reg)->getName() << '\n');
2072 if (VerifyCoalescing)
2073 MF->verify(this, "After register coalescing");
2077 /// print - Implement the dump method.
2078 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {