1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
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 a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
38 STATISTIC(numJoins , "Number of interval joins performed");
39 STATISTIC(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends , "Number of copies extended");
41 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
42 STATISTIC(numAborts , "Number of times interval joining aborted");
44 char SimpleRegisterCoalescing::ID = 0;
47 EnableJoining("join-liveintervals",
48 cl::desc("Coalesce copies (default=true)"),
52 NewHeuristic("new-coalescer-heuristic",
53 cl::desc("Use new coalescer heuristic"),
57 CommuteDef("coalescer-commute-instrs",
58 cl::init(false), cl::Hidden);
60 RegisterPass<SimpleRegisterCoalescing>
61 X("simple-register-coalescing", "Simple Register Coalescing");
63 // Declare that we implement the RegisterCoalescer interface
64 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
67 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
69 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addPreserved<LiveIntervals>();
71 AU.addPreserved<MachineLoopInfo>();
72 AU.addPreservedID(MachineDominatorsID);
73 AU.addPreservedID(PHIEliminationID);
74 AU.addPreservedID(TwoAddressInstructionPassID);
75 AU.addRequired<LiveVariables>();
76 AU.addRequired<LiveIntervals>();
77 AU.addRequired<MachineLoopInfo>();
78 MachineFunctionPass::getAnalysisUsage(AU);
81 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
82 /// being the source and IntB being the dest, thus this defines a value number
83 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
84 /// see if we can merge these two pieces of B into a single value number,
85 /// eliminating a copy. For example:
89 /// B1 = A3 <- this copy
91 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
92 /// value number to be replaced with B0 (which simplifies the B liveinterval).
94 /// This returns true if an interval was modified.
96 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
98 MachineInstr *CopyMI) {
99 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
101 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
102 // the example above.
103 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
104 VNInfo *BValNo = BLR->valno;
106 // Get the location that B is defined at. Two options: either this value has
107 // an unknown definition point or it is defined at CopyIdx. If unknown, we
109 if (!BValNo->reg) return false;
110 assert(BValNo->def == CopyIdx &&
111 "Copy doesn't define the value?");
113 // AValNo is the value number in A that defines the copy, A3 in the example.
114 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
115 VNInfo *AValNo = ALR->valno;
117 // If AValNo is defined as a copy from IntB, we can potentially process this.
118 // Get the instruction that defines this value number.
119 unsigned SrcReg = AValNo->reg;
120 if (!SrcReg) return false; // Not defined by a copy.
122 // If the value number is not defined by a copy instruction, ignore it.
124 // If the source register comes from an interval other than IntB, we can't
126 if (rep(SrcReg) != IntB.reg) return false;
128 // Get the LiveRange in IntB that this value number starts with.
129 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
131 // Make sure that the end of the live range is inside the same block as
133 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
135 ValLREndInst->getParent() != CopyMI->getParent()) return false;
137 // Okay, we now know that ValLR ends in the same block that the CopyMI
138 // live-range starts. If there are no intervening live ranges between them in
139 // IntB, we can merge them.
140 if (ValLR+1 != BLR) return false;
142 // If a live interval is a physical register, conservatively check if any
143 // of its sub-registers is overlapping the live interval of the virtual
144 // register. If so, do not coalesce.
145 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
146 *tri_->getSubRegisters(IntB.reg)) {
147 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
148 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
149 DOUT << "Interfere with sub-register ";
150 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
155 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
157 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
158 // We are about to delete CopyMI, so need to remove it as the 'instruction
159 // that defines this value #'. Update the the valnum with the new defining
161 BValNo->def = FillerStart;
164 // Okay, we can merge them. We need to insert a new liverange:
165 // [ValLR.end, BLR.begin) of either value number, then we merge the
166 // two value numbers.
167 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
169 // If the IntB live range is assigned to a physical register, and if that
170 // physreg has aliases,
171 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
172 // Update the liveintervals of sub-registers.
173 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
174 LiveInterval &AliasLI = li_->getInterval(*AS);
175 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
176 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
180 // Okay, merge "B1" into the same value number as "B0".
181 if (BValNo != ValLR->valno)
182 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
183 DOUT << " result = "; IntB.print(DOUT, tri_);
186 // If the source instruction was killing the source register before the
187 // merge, unset the isKill marker given the live range has been extended.
188 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
190 ValLREndInst->getOperand(UIdx).setIsKill(false);
196 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
197 /// being the source and IntB being the dest, thus this defines a value number
198 /// in IntB. If the source value number (in IntA) is defined by a commutable
199 /// instruction and its other operand is coalesced to the copy dest register,
200 /// see if we can transform the copy into a noop by commuting the definition. For
203 /// A3 = op A2 B0<kill>
205 /// B1 = A3 <- this copy
207 /// = op A3 <- more uses
211 /// B2 = op B0 A2<kill>
213 /// B1 = B2 <- now an identify copy
215 /// = op B2 <- more uses
217 /// This returns true if an interval was modified.
219 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
221 MachineInstr *CopyMI) {
222 if (!CommuteDef) return false;
224 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
226 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
227 // the example above.
228 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
229 VNInfo *BValNo = BLR->valno;
231 // Get the location that B is defined at. Two options: either this value has
232 // an unknown definition point or it is defined at CopyIdx. If unknown, we
234 if (!BValNo->reg) return false;
235 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
237 // AValNo is the value number in A that defines the copy, A3 in the example.
238 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
239 VNInfo *AValNo = ALR->valno;
240 // If other defs can reach uses of this def, then it's not safe to perform
242 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
244 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
245 const TargetInstrDesc &TID = DefMI->getDesc();
246 if (!TID.isCommutable())
249 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
250 MachineOperand &MO = DefMI->getOperand(i);
251 if (!MO.isRegister()) continue;
252 unsigned Reg = MO.getReg();
253 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
254 if (rep(Reg) == IntA.reg) {
255 // If the dest register comes from an interval other than IntA, we
256 // can't handle this.
262 // FIXME: Being overly careful here. We just need to figure out the
263 // which register operand will become the new def.
269 // Something like %reg1024 = add %reg1024, %reg1024
272 MachineOperand &MO = DefMI->getOperand(Idx);
273 unsigned NewReg = MO.getReg();
274 if (rep(NewReg) != IntB.reg || !MO.isKill())
277 // Make sure there are no other definitions of IntB that would reach the
278 // uses which the new definition can reach.
279 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
281 if (AI->valno != AValNo) continue;
282 LiveInterval::Ranges::iterator BI =
283 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
284 if (BI != IntB.ranges.begin())
286 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
287 if (BI->valno == BLR->valno)
289 if (BI->start <= AI->start && BI->end > AI->start)
291 if (BI->start > AI->start && BI->start < AI->end)
296 // Commute def machine instr.
297 MachineBasicBlock *MBB = DefMI->getParent();
298 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
299 if (NewMI != DefMI) {
300 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
301 MBB->insert(DefMI, NewMI);
304 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg);
305 NewMI->getOperand(OpIdx).setIsKill();
307 // Update uses of IntA of the specific Val# with IntB.
308 bool BHasPHIKill = BValNo->hasPHIKill;
309 SmallVector<VNInfo*, 4> BDeadValNos;
310 SmallVector<unsigned, 4> BKills;
311 std::map<unsigned, unsigned> BExtend;
312 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
313 UE = mri_->use_end(); UI != UE;) {
314 MachineOperand &UseMO = UI.getOperand();
316 MachineInstr *UseMI = UseMO.getParent();
317 if (JoinedCopies.count(UseMI))
319 unsigned UseIdx = li_->getInstructionIndex(UseMI);
320 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
321 if (ULR->valno != AValNo)
323 UseMO.setReg(NewReg);
325 BKills.push_back(li_->getUseIndex(UseIdx)+1);
326 if (UseMI != CopyMI) {
327 unsigned SrcReg, DstReg;
328 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
330 unsigned repDstReg = rep(DstReg);
331 if (repDstReg != IntB.reg) {
332 // Update dst register interval val# since its source register has
334 LiveInterval &DLI = li_->getInterval(repDstReg);
335 LiveInterval::iterator DLR =
336 DLI.FindLiveRangeContaining(li_->getDefIndex(UseIdx));
337 DLR->valno->reg = NewReg;
338 ChangedCopies.insert(UseMI);
340 // This copy will become a noop. If it's defining a new val#,
341 // remove that val# as well. However this live range is being
342 // extended to the end of the existing live range defined by the copy.
343 unsigned DefIdx = li_->getDefIndex(UseIdx);
344 LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
345 BHasPHIKill |= DLR->valno->hasPHIKill;
346 assert(DLR->valno->def == DefIdx);
347 BDeadValNos.push_back(DLR->valno);
348 BExtend[DLR->start] = DLR->end;
349 JoinedCopies.insert(UseMI);
350 // If this is a kill but it's going to be removed, the last use
351 // of the same val# is the new kill.
352 if (UseMO.isKill()) {
359 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
360 // simply extend BLR if CopyMI doesn't end the range.
361 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
363 IntB.removeValNo(BValNo);
364 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
365 IntB.removeValNo(BDeadValNos[i]);
366 VNInfo *ValNo = IntB.getNextValue(ALR->start, 0, li_->getVNInfoAllocator());
367 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
369 if (AI->valno != AValNo) continue;
370 unsigned End = AI->end;
371 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
372 if (EI != BExtend.end())
374 IntB.addRange(LiveRange(AI->start, End, ValNo));
376 IntB.addKills(ValNo, BKills);
377 ValNo->hasPHIKill = BHasPHIKill;
379 DOUT << " result = "; IntB.print(DOUT, tri_);
382 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
383 IntA.removeValNo(AValNo);
384 DOUT << " result = "; IntA.print(DOUT, tri_);
391 /// AddSubRegIdxPairs - Recursively mark all the registers represented by the
392 /// specified register as sub-registers. The recursion level is expected to be
394 void SimpleRegisterCoalescing::AddSubRegIdxPairs(unsigned Reg, unsigned SubIdx) {
395 std::vector<unsigned> &JoinedRegs = r2rRevMap_[Reg];
396 for (unsigned i = 0, e = JoinedRegs.size(); i != e; ++i) {
397 SubRegIdxes.push_back(std::make_pair(JoinedRegs[i], SubIdx));
398 AddSubRegIdxPairs(JoinedRegs[i], SubIdx);
402 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
404 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
406 MachineBasicBlock *MBB = CopyMI->getParent();
407 const MachineLoop *L = loopInfo->getLoopFor(MBB);
410 if (MBB != L->getLoopLatch())
413 DstReg = rep(DstReg);
414 LiveInterval &LI = li_->getInterval(DstReg);
415 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
416 LiveInterval::const_iterator DstLR =
417 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
418 if (DstLR == LI.end())
420 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
421 if (DstLR->valno->kills.size() == 1 &&
422 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
427 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
428 /// which are the src/dst of the copy instruction CopyMI. This returns true
429 /// if the copy was successfully coalesced away. If it is not currently
430 /// possible to coalesce this interval, but it may be possible if other
431 /// things get coalesced, then it returns true by reference in 'Again'.
432 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
433 MachineInstr *CopyMI = TheCopy.MI;
436 if (JoinedCopies.count(CopyMI))
437 return false; // Already done.
439 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
441 // Get representative registers.
442 unsigned SrcReg = TheCopy.SrcReg;
443 unsigned DstReg = TheCopy.DstReg;
445 // CopyMI has been modified due to commuting.
446 if (ChangedCopies.count(CopyMI)) {
447 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
449 else if (CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
450 DstReg = CopyMI->getOperand(0).getReg();
451 SrcReg = CopyMI->getOperand(1).getReg();
453 assert(0 && "Unrecognized move instruction!");
454 TheCopy.SrcReg = SrcReg;
455 TheCopy.DstReg = DstReg;
456 ChangedCopies.erase(CopyMI);
459 unsigned repSrcReg = rep(SrcReg);
460 unsigned repDstReg = rep(DstReg);
462 // If they are already joined we continue.
463 if (repSrcReg == repDstReg) {
464 DOUT << "\tCopy already coalesced.\n";
465 return false; // Not coalescable.
468 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(repSrcReg);
469 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(repDstReg);
471 // If they are both physical registers, we cannot join them.
472 if (SrcIsPhys && DstIsPhys) {
473 DOUT << "\tCan not coalesce physregs.\n";
474 return false; // Not coalescable.
477 // We only join virtual registers with allocatable physical registers.
478 if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
479 DOUT << "\tSrc reg is unallocatable physreg.\n";
480 return false; // Not coalescable.
482 if (DstIsPhys && !allocatableRegs_[repDstReg]) {
483 DOUT << "\tDst reg is unallocatable physreg.\n";
484 return false; // Not coalescable.
487 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
488 unsigned RealDstReg = 0;
490 unsigned SubIdx = CopyMI->getOperand(2).getImm();
492 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
493 // coalesced with AX.
494 repSrcReg = tri_->getSubReg(repSrcReg, SubIdx);
495 else if (DstIsPhys) {
496 // If this is a extract_subreg where dst is a physical register, e.g.
497 // cl = EXTRACT_SUBREG reg1024, 1
498 // then create and update the actual physical register allocated to RHS.
499 const TargetRegisterClass *RC = mri_->getRegClass(repSrcReg);
500 for (const unsigned *SRs = tri_->getSuperRegisters(repDstReg);
501 unsigned SR = *SRs; ++SRs) {
502 if (repDstReg == tri_->getSubReg(SR, SubIdx) &&
508 assert(RealDstReg && "Invalid extra_subreg instruction!");
510 // For this type of EXTRACT_SUBREG, conservatively
511 // check if the live interval of the source register interfere with the
512 // actual super physical register we are trying to coalesce with.
513 LiveInterval &RHS = li_->getInterval(repSrcReg);
514 if (li_->hasInterval(RealDstReg) &&
515 RHS.overlaps(li_->getInterval(RealDstReg))) {
516 DOUT << "Interfere with register ";
517 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
518 return false; // Not coalescable
520 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
521 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
522 DOUT << "Interfere with sub-register ";
523 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
524 return false; // Not coalescable
527 unsigned SrcSize= li_->getInterval(repSrcReg).getSize() / InstrSlots::NUM;
528 unsigned DstSize= li_->getInterval(repDstReg).getSize() / InstrSlots::NUM;
529 const TargetRegisterClass *RC=mf_->getRegInfo().getRegClass(repDstReg);
530 unsigned Threshold = allocatableRCRegs_[RC].count();
531 // Be conservative. If both sides are virtual registers, do not coalesce
532 // if this will cause a high use density interval to target a smaller set
534 if (DstSize > Threshold || SrcSize > Threshold) {
535 LiveVariables::VarInfo &svi = lv_->getVarInfo(repSrcReg);
536 LiveVariables::VarInfo &dvi = lv_->getVarInfo(repDstReg);
537 if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
538 Again = true; // May be possible to coalesce later.
543 } else if (differingRegisterClasses(repSrcReg, repDstReg)) {
544 // If they are not of the same register class, we cannot join them.
545 DOUT << "\tSrc/Dest are different register classes.\n";
546 // Allow the coalescer to try again in case either side gets coalesced to
547 // a physical register that's compatible with the other side. e.g.
548 // r1024 = MOV32to32_ r1025
549 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
550 Again = true; // May be possible to coalesce later.
554 LiveInterval &SrcInt = li_->getInterval(repSrcReg);
555 LiveInterval &DstInt = li_->getInterval(repDstReg);
556 assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
557 "Register mapping is horribly broken!");
559 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
560 DOUT << " and "; DstInt.print(DOUT, tri_);
563 // Check if it is necessary to propagate "isDead" property before intervals
565 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
566 bool isDead = mopd->isDead();
567 bool isShorten = false;
568 unsigned SrcStart = 0, RemoveStart = 0;
569 unsigned SrcEnd = 0, RemoveEnd = 0;
571 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
572 LiveInterval::iterator SrcLR =
573 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
574 RemoveStart = SrcStart = SrcLR->start;
575 RemoveEnd = SrcEnd = SrcLR->end;
576 // The instruction which defines the src is only truly dead if there are
577 // no intermediate uses and there isn't a use beyond the copy.
578 // FIXME: find the last use, mark is kill and shorten the live range.
579 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
583 MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
585 // Shorten the liveinterval to the end of last use.
589 RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
592 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
594 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
596 // A dead def should have a single cycle interval.
603 // We need to be careful about coalescing a source physical register with a
604 // virtual register. Once the coalescing is done, it cannot be broken and
605 // these are not spillable! If the destination interval uses are far away,
606 // think twice about coalescing them!
607 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
608 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
609 unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
610 unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
611 const TargetRegisterClass *RC = mf_->getRegInfo().getRegClass(JoinVReg);
612 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
613 if (TheCopy.isBackEdge)
614 Threshold *= 2; // Favors back edge copies.
616 // If the virtual register live interval is long but it has low use desity,
617 // do not join them, instead mark the physical register as its allocation
619 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
620 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
621 if (Length > Threshold &&
622 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
623 JoinVInt.preference = JoinPReg;
625 DOUT << "\tMay tie down a physical register, abort!\n";
626 Again = true; // May be possible to coalesce later.
631 // Okay, attempt to join these two intervals. On failure, this returns false.
632 // Otherwise, if one of the intervals being joined is a physreg, this method
633 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
634 // been modified, so we can use this information below to update aliases.
635 bool Swapped = false;
636 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
638 // Result of the copy is dead. Propagate this property.
640 assert(TargetRegisterInfo::isPhysicalRegister(repSrcReg) &&
641 "Live-in must be a physical register!");
642 // Live-in to the function but dead. Remove it from entry live-in set.
643 // JoinIntervals may end up swapping the two intervals.
644 mf_->begin()->removeLiveIn(repSrcReg);
646 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
648 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
655 if (isShorten || isDead) {
656 // Shorten the destination live interval.
658 SrcInt.removeRange(RemoveStart, RemoveEnd, true);
661 // Coalescing failed.
663 // If we can eliminate the copy without merging the live ranges, do so now.
665 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
666 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
667 JoinedCopies.insert(CopyMI);
672 // Otherwise, we are unable to join the intervals.
673 DOUT << "Interference!\n";
674 Again = true; // May be possible to coalesce later.
678 LiveInterval *ResSrcInt = &SrcInt;
679 LiveInterval *ResDstInt = &DstInt;
681 std::swap(repSrcReg, repDstReg);
682 std::swap(ResSrcInt, ResDstInt);
684 assert(TargetRegisterInfo::isVirtualRegister(repSrcReg) &&
685 "LiveInterval::join didn't work right!");
687 // If we're about to merge live ranges into a physical register live range,
688 // we have to update any aliased register's live ranges to indicate that they
689 // have clobbered values for this range.
690 if (TargetRegisterInfo::isPhysicalRegister(repDstReg)) {
691 // Unset unnecessary kills.
692 if (!ResDstInt->containsOneValue()) {
693 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
694 E = ResSrcInt->end(); I != E; ++I)
695 unsetRegisterKills(I->start, I->end, repDstReg);
698 // If this is a extract_subreg where dst is a physical register, e.g.
699 // cl = EXTRACT_SUBREG reg1024, 1
700 // then create and update the actual physical register allocated to RHS.
702 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
703 SmallSet<const VNInfo*, 4> CopiedValNos;
704 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
705 E = ResSrcInt->ranges.end(); I != E; ++I) {
706 LiveInterval::const_iterator DstLR =
707 ResDstInt->FindLiveRangeContaining(I->start);
708 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
709 const VNInfo *DstValNo = DstLR->valno;
710 if (CopiedValNos.insert(DstValNo)) {
711 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->reg,
712 li_->getVNInfoAllocator());
713 ValNo->hasPHIKill = DstValNo->hasPHIKill;
714 RealDstInt.addKills(ValNo, DstValNo->kills);
715 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
718 repDstReg = RealDstReg;
721 // Update the liveintervals of sub-registers.
722 for (const unsigned *AS = tri_->getSubRegisters(repDstReg); *AS; ++AS)
723 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
724 li_->getVNInfoAllocator());
726 // Merge use info if the destination is a virtual register.
727 LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
728 LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
729 dVI.NumUses += sVI.NumUses;
732 // Remember these liveintervals have been joined.
733 JoinedLIs.set(repSrcReg - TargetRegisterInfo::FirstVirtualRegister);
734 if (TargetRegisterInfo::isVirtualRegister(repDstReg))
735 JoinedLIs.set(repDstReg - TargetRegisterInfo::FirstVirtualRegister);
737 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
739 // Make sure we allocate the larger super-register.
740 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
741 std::swap(repSrcReg, repDstReg);
742 std::swap(ResSrcInt, ResDstInt);
744 unsigned SubIdx = CopyMI->getOperand(2).getImm();
745 SubRegIdxes.push_back(std::make_pair(repSrcReg, SubIdx));
746 AddSubRegIdxPairs(repSrcReg, SubIdx);
750 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
751 e = ResSrcInt->vni_end(); i != e; ++i) {
752 const VNInfo *vni = *i;
753 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
754 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
755 unsigned SrcReg, DstReg;
757 JoinedCopies.count(CopyMI) == 0 &&
758 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
759 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
760 JoinQueue->push(CopyRec(CopyMI, SrcReg, DstReg, LoopDepth,
761 isBackEdgeCopy(CopyMI, DstReg)));
767 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
770 // repSrcReg is guarateed to be the register whose live interval that is
772 li_->removeInterval(repSrcReg);
773 r2rMap_[repSrcReg] = repDstReg;
774 r2rRevMap_[repDstReg].push_back(repSrcReg);
776 // Finally, delete the copy instruction.
777 JoinedCopies.insert(CopyMI);
782 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
783 /// compute what the resultant value numbers for each value in the input two
784 /// ranges will be. This is complicated by copies between the two which can
785 /// and will commonly cause multiple value numbers to be merged into one.
787 /// VN is the value number that we're trying to resolve. InstDefiningValue
788 /// keeps track of the new InstDefiningValue assignment for the result
789 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
790 /// whether a value in this or other is a copy from the opposite set.
791 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
792 /// already been assigned.
794 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
795 /// contains the value number the copy is from.
797 static unsigned ComputeUltimateVN(VNInfo *VNI,
798 SmallVector<VNInfo*, 16> &NewVNInfo,
799 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
800 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
801 SmallVector<int, 16> &ThisValNoAssignments,
802 SmallVector<int, 16> &OtherValNoAssignments) {
803 unsigned VN = VNI->id;
805 // If the VN has already been computed, just return it.
806 if (ThisValNoAssignments[VN] >= 0)
807 return ThisValNoAssignments[VN];
808 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
810 // If this val is not a copy from the other val, then it must be a new value
811 // number in the destination.
812 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
813 if (I == ThisFromOther.end()) {
814 NewVNInfo.push_back(VNI);
815 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
817 VNInfo *OtherValNo = I->second;
819 // Otherwise, this *is* a copy from the RHS. If the other side has already
820 // been computed, return it.
821 if (OtherValNoAssignments[OtherValNo->id] >= 0)
822 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
824 // Mark this value number as currently being computed, then ask what the
825 // ultimate value # of the other value is.
826 ThisValNoAssignments[VN] = -2;
827 unsigned UltimateVN =
828 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
829 OtherValNoAssignments, ThisValNoAssignments);
830 return ThisValNoAssignments[VN] = UltimateVN;
833 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
834 return std::find(V.begin(), V.end(), Val) != V.end();
837 /// SimpleJoin - Attempt to joint the specified interval into this one. The
838 /// caller of this method must guarantee that the RHS only contains a single
839 /// value number and that the RHS is not defined by a copy from this
840 /// interval. This returns false if the intervals are not joinable, or it
841 /// joins them and returns true.
842 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
843 assert(RHS.containsOneValue());
845 // Some number (potentially more than one) value numbers in the current
846 // interval may be defined as copies from the RHS. Scan the overlapping
847 // portions of the LHS and RHS, keeping track of this and looking for
848 // overlapping live ranges that are NOT defined as copies. If these exist, we
851 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
852 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
854 if (LHSIt->start < RHSIt->start) {
855 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
856 if (LHSIt != LHS.begin()) --LHSIt;
857 } else if (RHSIt->start < LHSIt->start) {
858 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
859 if (RHSIt != RHS.begin()) --RHSIt;
862 SmallVector<VNInfo*, 8> EliminatedLHSVals;
865 // Determine if these live intervals overlap.
866 bool Overlaps = false;
867 if (LHSIt->start <= RHSIt->start)
868 Overlaps = LHSIt->end > RHSIt->start;
870 Overlaps = RHSIt->end > LHSIt->start;
872 // If the live intervals overlap, there are two interesting cases: if the
873 // LHS interval is defined by a copy from the RHS, it's ok and we record
874 // that the LHS value # is the same as the RHS. If it's not, then we cannot
875 // coalesce these live ranges and we bail out.
877 // If we haven't already recorded that this value # is safe, check it.
878 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
879 // Copy from the RHS?
880 unsigned SrcReg = LHSIt->valno->reg;
881 if (rep(SrcReg) != RHS.reg)
882 return false; // Nope, bail out.
884 EliminatedLHSVals.push_back(LHSIt->valno);
887 // We know this entire LHS live range is okay, so skip it now.
888 if (++LHSIt == LHSEnd) break;
892 if (LHSIt->end < RHSIt->end) {
893 if (++LHSIt == LHSEnd) break;
895 // One interesting case to check here. It's possible that we have
896 // something like "X3 = Y" which defines a new value number in the LHS,
897 // and is the last use of this liverange of the RHS. In this case, we
898 // want to notice this copy (so that it gets coalesced away) even though
899 // the live ranges don't actually overlap.
900 if (LHSIt->start == RHSIt->end) {
901 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
902 // We already know that this value number is going to be merged in
903 // if coalescing succeeds. Just skip the liverange.
904 if (++LHSIt == LHSEnd) break;
906 // Otherwise, if this is a copy from the RHS, mark it as being merged
908 if (rep(LHSIt->valno->reg) == RHS.reg) {
909 EliminatedLHSVals.push_back(LHSIt->valno);
911 // We know this entire LHS live range is okay, so skip it now.
912 if (++LHSIt == LHSEnd) break;
917 if (++RHSIt == RHSEnd) break;
921 // If we got here, we know that the coalescing will be successful and that
922 // the value numbers in EliminatedLHSVals will all be merged together. Since
923 // the most common case is that EliminatedLHSVals has a single number, we
924 // optimize for it: if there is more than one value, we merge them all into
925 // the lowest numbered one, then handle the interval as if we were merging
926 // with one value number.
928 if (EliminatedLHSVals.size() > 1) {
929 // Loop through all the equal value numbers merging them into the smallest
931 VNInfo *Smallest = EliminatedLHSVals[0];
932 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
933 if (EliminatedLHSVals[i]->id < Smallest->id) {
934 // Merge the current notion of the smallest into the smaller one.
935 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
936 Smallest = EliminatedLHSVals[i];
938 // Merge into the smallest.
939 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
944 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
945 LHSValNo = EliminatedLHSVals[0];
948 // Okay, now that there is a single LHS value number that we're merging the
949 // RHS into, update the value number info for the LHS to indicate that the
950 // value number is defined where the RHS value number was.
951 const VNInfo *VNI = RHS.getValNumInfo(0);
952 LHSValNo->def = VNI->def;
953 LHSValNo->reg = VNI->reg;
955 // Okay, the final step is to loop over the RHS live intervals, adding them to
957 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
958 LHS.addKills(LHSValNo, VNI->kills);
959 LHS.MergeRangesInAsValue(RHS, LHSValNo);
960 LHS.weight += RHS.weight;
961 if (RHS.preference && !LHS.preference)
962 LHS.preference = RHS.preference;
967 /// JoinIntervals - Attempt to join these two intervals. On failure, this
968 /// returns false. Otherwise, if one of the intervals being joined is a
969 /// physreg, this method always canonicalizes LHS to be it. The output
970 /// "RHS" will not have been modified, so we can use this information
971 /// below to update aliases.
972 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
973 LiveInterval &RHS, bool &Swapped) {
974 // Compute the final value assignment, assuming that the live ranges can be
976 SmallVector<int, 16> LHSValNoAssignments;
977 SmallVector<int, 16> RHSValNoAssignments;
978 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
979 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
980 SmallVector<VNInfo*, 16> NewVNInfo;
982 // If a live interval is a physical register, conservatively check if any
983 // of its sub-registers is overlapping the live interval of the virtual
984 // register. If so, do not coalesce.
985 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
986 *tri_->getSubRegisters(LHS.reg)) {
987 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
988 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
989 DOUT << "Interfere with sub-register ";
990 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
993 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
994 *tri_->getSubRegisters(RHS.reg)) {
995 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
996 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
997 DOUT << "Interfere with sub-register ";
998 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1003 // Compute ultimate value numbers for the LHS and RHS values.
1004 if (RHS.containsOneValue()) {
1005 // Copies from a liveinterval with a single value are simple to handle and
1006 // very common, handle the special case here. This is important, because
1007 // often RHS is small and LHS is large (e.g. a physreg).
1009 // Find out if the RHS is defined as a copy from some value in the LHS.
1010 int RHSVal0DefinedFromLHS = -1;
1012 VNInfo *RHSValNoInfo = NULL;
1013 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1014 unsigned RHSSrcReg = RHSValNoInfo0->reg;
1015 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1016 // If RHS is not defined as a copy from the LHS, we can use simpler and
1017 // faster checks to see if the live ranges are coalescable. This joiner
1018 // can't swap the LHS/RHS intervals though.
1019 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1020 return SimpleJoin(LHS, RHS);
1022 RHSValNoInfo = RHSValNoInfo0;
1025 // It was defined as a copy from the LHS, find out what value # it is.
1026 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1027 RHSValID = RHSValNoInfo->id;
1028 RHSVal0DefinedFromLHS = RHSValID;
1031 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1032 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1033 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1035 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1036 // should now get updated.
1037 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1040 unsigned VN = VNI->id;
1041 if (unsigned LHSSrcReg = VNI->reg) {
1042 if (rep(LHSSrcReg) != RHS.reg) {
1043 // If this is not a copy from the RHS, its value number will be
1044 // unmodified by the coalescing.
1045 NewVNInfo[VN] = VNI;
1046 LHSValNoAssignments[VN] = VN;
1047 } else if (RHSValID == -1) {
1048 // Otherwise, it is a copy from the RHS, and we don't already have a
1049 // value# for it. Keep the current value number, but remember it.
1050 LHSValNoAssignments[VN] = RHSValID = VN;
1051 NewVNInfo[VN] = RHSValNoInfo;
1052 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1054 // Otherwise, use the specified value #.
1055 LHSValNoAssignments[VN] = RHSValID;
1056 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1057 NewVNInfo[VN] = RHSValNoInfo;
1058 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1062 NewVNInfo[VN] = VNI;
1063 LHSValNoAssignments[VN] = VN;
1067 assert(RHSValID != -1 && "Didn't find value #?");
1068 RHSValNoAssignments[0] = RHSValID;
1069 if (RHSVal0DefinedFromLHS != -1) {
1070 // This path doesn't go through ComputeUltimateVN so just set
1072 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1075 // Loop over the value numbers of the LHS, seeing if any are defined from
1077 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1080 unsigned ValSrcReg = VNI->reg;
1081 if (VNI->def == ~1U ||ValSrcReg == 0) // Src not defined by a copy?
1084 // DstReg is known to be a register in the LHS interval. If the src is
1085 // from the RHS interval, we can use its value #.
1086 if (rep(ValSrcReg) != RHS.reg)
1089 // Figure out the value # from the RHS.
1090 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1093 // Loop over the value numbers of the RHS, seeing if any are defined from
1095 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1098 unsigned ValSrcReg = VNI->reg;
1099 if (VNI->def == ~1U || ValSrcReg == 0) // Src not defined by a copy?
1102 // DstReg is known to be a register in the RHS interval. If the src is
1103 // from the LHS interval, we can use its value #.
1104 if (rep(ValSrcReg) != LHS.reg)
1107 // Figure out the value # from the LHS.
1108 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1111 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1112 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1113 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1115 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1118 unsigned VN = VNI->id;
1119 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1121 ComputeUltimateVN(VNI, NewVNInfo,
1122 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1123 LHSValNoAssignments, RHSValNoAssignments);
1125 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1128 unsigned VN = VNI->id;
1129 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1131 // If this value number isn't a copy from the LHS, it's a new number.
1132 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1133 NewVNInfo.push_back(VNI);
1134 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1138 ComputeUltimateVN(VNI, NewVNInfo,
1139 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1140 RHSValNoAssignments, LHSValNoAssignments);
1144 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1145 // interval lists to see if these intervals are coalescable.
1146 LiveInterval::const_iterator I = LHS.begin();
1147 LiveInterval::const_iterator IE = LHS.end();
1148 LiveInterval::const_iterator J = RHS.begin();
1149 LiveInterval::const_iterator JE = RHS.end();
1151 // Skip ahead until the first place of potential sharing.
1152 if (I->start < J->start) {
1153 I = std::upper_bound(I, IE, J->start);
1154 if (I != LHS.begin()) --I;
1155 } else if (J->start < I->start) {
1156 J = std::upper_bound(J, JE, I->start);
1157 if (J != RHS.begin()) --J;
1161 // Determine if these two live ranges overlap.
1163 if (I->start < J->start) {
1164 Overlaps = I->end > J->start;
1166 Overlaps = J->end > I->start;
1169 // If so, check value # info to determine if they are really different.
1171 // If the live range overlap will map to the same value number in the
1172 // result liverange, we can still coalesce them. If not, we can't.
1173 if (LHSValNoAssignments[I->valno->id] !=
1174 RHSValNoAssignments[J->valno->id])
1178 if (I->end < J->end) {
1187 // Update kill info. Some live ranges are extended due to copy coalescing.
1188 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1189 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1190 VNInfo *VNI = I->first;
1191 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1192 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1193 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1194 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1197 // Update kill info. Some live ranges are extended due to copy coalescing.
1198 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1199 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1200 VNInfo *VNI = I->first;
1201 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1202 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1203 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1204 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1207 // If we get here, we know that we can coalesce the live ranges. Ask the
1208 // intervals to coalesce themselves now.
1209 if ((RHS.ranges.size() > LHS.ranges.size() &&
1210 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1211 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1212 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1215 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1222 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1223 // depth of the basic block (the unsigned), and then on the MBB number.
1224 struct DepthMBBCompare {
1225 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1226 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1227 if (LHS.first > RHS.first) return true; // Deeper loops first
1228 return LHS.first == RHS.first &&
1229 LHS.second->getNumber() < RHS.second->getNumber();
1234 /// getRepIntervalSize - Returns the size of the interval that represents the
1235 /// specified register.
1237 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1238 return Rc->getRepIntervalSize(Reg);
1241 /// CopyRecSort::operator - Join priority queue sorting function.
1243 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1244 // Inner loops first.
1245 if (left.LoopDepth > right.LoopDepth)
1247 else if (left.LoopDepth == right.LoopDepth) {
1248 if (left.isBackEdge && !right.isBackEdge)
1250 else if (left.isBackEdge == right.isBackEdge) {
1251 // Join virtuals to physical registers first.
1252 bool LDstIsPhys = TargetRegisterInfo::isPhysicalRegister(left.DstReg);
1253 bool LSrcIsPhys = TargetRegisterInfo::isPhysicalRegister(left.SrcReg);
1254 bool LIsPhys = LDstIsPhys || LSrcIsPhys;
1255 bool RDstIsPhys = TargetRegisterInfo::isPhysicalRegister(right.DstReg);
1256 bool RSrcIsPhys = TargetRegisterInfo::isPhysicalRegister(right.SrcReg);
1257 bool RIsPhys = RDstIsPhys || RSrcIsPhys;
1258 if (LIsPhys && !RIsPhys)
1260 else if (LIsPhys == RIsPhys) {
1261 // Join shorter intervals first.
1265 LSize = LDstIsPhys ? 0 : JPQ->getRepIntervalSize(left.DstReg);
1266 LSize += LSrcIsPhys ? 0 : JPQ->getRepIntervalSize(left.SrcReg);
1267 RSize = RDstIsPhys ? 0 : JPQ->getRepIntervalSize(right.DstReg);
1268 RSize += RSrcIsPhys ? 0 : JPQ->getRepIntervalSize(right.SrcReg);
1270 LSize = std::min(JPQ->getRepIntervalSize(left.DstReg),
1271 JPQ->getRepIntervalSize(left.SrcReg));
1272 RSize = std::min(JPQ->getRepIntervalSize(right.DstReg),
1273 JPQ->getRepIntervalSize(right.SrcReg));
1283 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1284 std::vector<CopyRec> &TryAgain) {
1285 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1287 std::vector<CopyRec> VirtCopies;
1288 std::vector<CopyRec> PhysCopies;
1289 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1290 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1292 MachineInstr *Inst = MII++;
1294 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1295 unsigned SrcReg, DstReg;
1296 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1297 DstReg = Inst->getOperand(0).getReg();
1298 SrcReg = Inst->getOperand(1).getReg();
1299 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1302 unsigned repSrcReg = rep(SrcReg);
1303 unsigned repDstReg = rep(DstReg);
1304 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(repSrcReg);
1305 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(repDstReg);
1307 JoinQueue->push(CopyRec(Inst, SrcReg, DstReg, LoopDepth,
1308 isBackEdgeCopy(Inst, DstReg)));
1310 if (SrcIsPhys || DstIsPhys)
1311 PhysCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1313 VirtCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1320 // Try coalescing physical register + virtual register first.
1321 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1322 CopyRec &TheCopy = PhysCopies[i];
1324 if (!JoinCopy(TheCopy, Again))
1326 TryAgain.push_back(TheCopy);
1328 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1329 CopyRec &TheCopy = VirtCopies[i];
1331 if (!JoinCopy(TheCopy, Again))
1333 TryAgain.push_back(TheCopy);
1337 void SimpleRegisterCoalescing::joinIntervals() {
1338 DOUT << "********** JOINING INTERVALS ***********\n";
1341 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1343 JoinedLIs.resize(li_->getNumIntervals());
1346 std::vector<CopyRec> TryAgainList;
1347 if (loopInfo->begin() == loopInfo->end()) {
1348 // If there are no loops in the function, join intervals in function order.
1349 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1351 CopyCoalesceInMBB(I, TryAgainList);
1353 // Otherwise, join intervals in inner loops before other intervals.
1354 // Unfortunately we can't just iterate over loop hierarchy here because
1355 // there may be more MBB's than BB's. Collect MBB's for sorting.
1357 // Join intervals in the function prolog first. We want to join physical
1358 // registers with virtual registers before the intervals got too long.
1359 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1360 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1361 MachineBasicBlock *MBB = I;
1362 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1365 // Sort by loop depth.
1366 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1368 // Finally, join intervals in loop nest order.
1369 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1370 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1373 // Joining intervals can allow other intervals to be joined. Iteratively join
1374 // until we make no progress.
1376 SmallVector<CopyRec, 16> TryAgain;
1377 bool ProgressMade = true;
1378 while (ProgressMade) {
1379 ProgressMade = false;
1380 while (!JoinQueue->empty()) {
1381 CopyRec R = JoinQueue->pop();
1383 bool Success = JoinCopy(R, Again);
1385 ProgressMade = true;
1387 TryAgain.push_back(R);
1391 while (!TryAgain.empty()) {
1392 JoinQueue->push(TryAgain.back());
1393 TryAgain.pop_back();
1398 bool ProgressMade = true;
1399 while (ProgressMade) {
1400 ProgressMade = false;
1402 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1403 CopyRec &TheCopy = TryAgainList[i];
1406 bool Success = JoinCopy(TheCopy, Again);
1407 if (Success || !Again) {
1408 TheCopy.MI = 0; // Mark this one as done.
1409 ProgressMade = true;
1416 // Some live range has been lengthened due to colaescing, eliminate the
1417 // unnecessary kills.
1418 int RegNum = JoinedLIs.find_first();
1419 while (RegNum != -1) {
1420 unsigned Reg = RegNum + TargetRegisterInfo::FirstVirtualRegister;
1421 unsigned repReg = rep(Reg);
1422 LiveInterval &LI = li_->getInterval(repReg);
1423 LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
1424 for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
1425 MachineInstr *Kill = svi.Kills[i];
1426 // Suppose vr1 = op vr2, x
1427 // and vr1 and vr2 are coalesced. vr2 should still be marked kill
1428 // unless it is a two-address operand.
1429 if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
1431 if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
1432 unsetRegisterKill(Kill, repReg);
1434 RegNum = JoinedLIs.find_next(RegNum);
1440 DOUT << "*** Register mapping ***\n";
1441 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1443 DOUT << " reg " << i << " -> ";
1444 DEBUG(printRegName(r2rMap_[i]));
1449 /// Return true if the two specified registers belong to different register
1450 /// classes. The registers may be either phys or virt regs.
1451 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1452 unsigned RegB) const {
1454 // Get the register classes for the first reg.
1455 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1456 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1457 "Shouldn't consider two physregs!");
1458 return !mf_->getRegInfo().getRegClass(RegB)->contains(RegA);
1461 // Compare against the regclass for the second reg.
1462 const TargetRegisterClass *RegClass = mf_->getRegInfo().getRegClass(RegA);
1463 if (TargetRegisterInfo::isVirtualRegister(RegB))
1464 return RegClass != mf_->getRegInfo().getRegClass(RegB);
1466 return !RegClass->contains(RegB);
1469 /// FIXME: Make use MachineRegisterInfo use information for virtual registers.
1470 /// lastRegisterUse - Returns the last use of the specific register between
1471 /// cycles Start and End. It also returns the use operand by reference. It
1472 /// returns NULL if there are no uses.
1474 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1475 unsigned Reg, MachineOperand *&MOU) {
1476 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1479 // Skip deleted instructions
1480 MachineInstr *MI = li_->getInstructionFromIndex(e);
1481 while ((e - InstrSlots::NUM) >= s && !MI) {
1482 e -= InstrSlots::NUM;
1483 MI = li_->getInstructionFromIndex(e);
1485 if (e < s || MI == NULL)
1488 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1489 MachineOperand &MO = MI->getOperand(i);
1490 if (MO.isRegister() && MO.isUse() && MO.getReg() &&
1491 tri_->regsOverlap(rep(MO.getReg()), Reg)) {
1497 e -= InstrSlots::NUM;
1504 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1505 /// register. It returns NULL if the def is not found.
1506 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI,
1508 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1509 MachineOperand &MO = MI->getOperand(i);
1510 if (MO.isRegister() && MO.isDef() &&
1511 tri_->regsOverlap(rep(MO.getReg()), Reg))
1517 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1518 /// of the specific instruction.
1519 void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI,
1521 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1522 MachineOperand &MO = MI->getOperand(i);
1523 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1524 tri_->regsOverlap(rep(MO.getReg()), Reg))
1525 MO.setIsKill(false);
1529 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1530 /// between cycles Start and End.
1531 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1533 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1536 // Skip deleted instructions
1537 MachineInstr *MI = li_->getInstructionFromIndex(e);
1538 while ((e - InstrSlots::NUM) >= s && !MI) {
1539 e -= InstrSlots::NUM;
1540 MI = li_->getInstructionFromIndex(e);
1542 if (e < s || MI == NULL)
1545 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1546 MachineOperand &MO = MI->getOperand(i);
1547 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1548 tri_->regsOverlap(rep(MO.getReg()), Reg)) {
1549 MO.setIsKill(false);
1553 e -= InstrSlots::NUM;
1557 /// hasRegisterDef - True if the instruction defines the specific register.
1559 bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1560 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1561 MachineOperand &MO = MI->getOperand(i);
1562 if (MO.isRegister() && MO.isDef() &&
1563 tri_->regsOverlap(rep(MO.getReg()), Reg))
1569 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1570 if (TargetRegisterInfo::isPhysicalRegister(reg))
1571 cerr << tri_->getName(reg);
1573 cerr << "%reg" << reg;
1576 void SimpleRegisterCoalescing::releaseMemory() {
1577 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1578 r2rRevMap_[i].clear();
1582 SubRegIdxes.clear();
1583 JoinedCopies.clear();
1584 ChangedCopies.clear();
1587 static bool isZeroLengthInterval(LiveInterval *li) {
1588 for (LiveInterval::Ranges::const_iterator
1589 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1590 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1595 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1597 mri_ = &fn.getRegInfo();
1598 tm_ = &fn.getTarget();
1599 tri_ = tm_->getRegisterInfo();
1600 tii_ = tm_->getInstrInfo();
1601 li_ = &getAnalysis<LiveIntervals>();
1602 lv_ = &getAnalysis<LiveVariables>();
1603 loopInfo = &getAnalysis<MachineLoopInfo>();
1605 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1606 << "********** Function: "
1607 << ((Value*)mf_->getFunction())->getName() << '\n';
1609 allocatableRegs_ = tri_->getAllocatableSet(fn);
1610 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1611 E = tri_->regclass_end(); I != E; ++I)
1612 allocatableRCRegs_.insert(std::make_pair(*I,
1613 tri_->getAllocatableSet(fn, *I)));
1615 MachineRegisterInfo &RegInfo = mf_->getRegInfo();
1616 r2rMap_.grow(RegInfo.getLastVirtReg());
1617 r2rRevMap_.grow(RegInfo.getLastVirtReg());
1619 // Join (coalesce) intervals if requested.
1620 IndexedMap<unsigned, VirtReg2IndexFunctor> RegSubIdxMap;
1621 if (EnableJoining) {
1623 DOUT << "********** INTERVALS POST JOINING **********\n";
1624 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1625 I->second.print(DOUT, tri_);
1629 // Delete all coalesced copies.
1630 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1631 E = JoinedCopies.end(); I != E; ++I) {
1632 li_->RemoveMachineInstrFromMaps(*I);
1633 (*I)->eraseFromParent();
1637 // Transfer sub-registers info to MachineRegisterInfo now that coalescing
1638 // information is complete.
1639 RegSubIdxMap.grow(RegInfo.getLastVirtReg()+1);
1640 while (!SubRegIdxes.empty()) {
1641 std::pair<unsigned, unsigned> RI = SubRegIdxes.back();
1642 SubRegIdxes.pop_back();
1643 RegSubIdxMap[RI.first] = RI.second;
1647 // perform a final pass over the instructions and compute spill
1648 // weights, coalesce virtual registers and remove identity moves.
1649 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1650 mbbi != mbbe; ++mbbi) {
1651 MachineBasicBlock* mbb = mbbi;
1652 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1654 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1656 // if the move will be an identity move delete it
1657 unsigned srcReg, dstReg, RegRep;
1658 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1659 (RegRep = rep(srcReg)) == rep(dstReg)) {
1660 // remove from def list
1661 LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1662 MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1663 // If def of this move instruction is dead, remove its live range from
1664 // the dstination register's live interval.
1666 unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1667 LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1668 RegInt.removeRange(MLR->start, MoveIdx+1, true);
1670 li_->removeInterval(RegRep);
1672 li_->RemoveMachineInstrFromMaps(mii);
1673 mii = mbbi->erase(mii);
1676 SmallSet<unsigned, 4> UniqueUses;
1677 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1678 const MachineOperand &mop = mii->getOperand(i);
1679 if (mop.isRegister() && mop.getReg() &&
1680 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1681 // replace register with representative register
1682 unsigned OrigReg = mop.getReg();
1683 unsigned reg = rep(OrigReg);
1684 unsigned SubIdx = RegSubIdxMap[OrigReg];
1685 if (SubIdx && TargetRegisterInfo::isPhysicalRegister(reg))
1686 mii->getOperand(i).setReg(tri_->getSubReg(reg, SubIdx));
1688 mii->getOperand(i).setReg(reg);
1689 mii->getOperand(i).setSubReg(SubIdx);
1692 // Multiple uses of reg by the same instruction. It should not
1693 // contribute to spill weight again.
1694 if (UniqueUses.count(reg) != 0)
1696 LiveInterval &RegInt = li_->getInterval(reg);
1698 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1699 UniqueUses.insert(reg);
1707 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1708 LiveInterval &LI = I->second;
1709 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1710 // If the live interval length is essentially zero, i.e. in every live
1711 // range the use follows def immediately, it doesn't make sense to spill
1712 // it and hope it will be easier to allocate for this li.
1713 if (isZeroLengthInterval(&LI))
1714 LI.weight = HUGE_VALF;
1716 bool isLoad = false;
1717 if (li_->isReMaterializable(LI, isLoad)) {
1718 // If all of the definitions of the interval are re-materializable,
1719 // it is a preferred candidate for spilling. If non of the defs are
1720 // loads, then it's potentially very cheap to re-materialize.
1721 // FIXME: this gets much more complicated once we support non-trivial
1722 // re-materialization.
1730 // Slightly prefer live interval that has been assigned a preferred reg.
1734 // Divide the weight of the interval by its size. This encourages
1735 // spilling of intervals that are large and have few uses, and
1736 // discourages spilling of small intervals with many uses.
1737 LI.weight /= LI.getSize();
1745 /// print - Implement the dump method.
1746 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1750 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1751 return new SimpleRegisterCoalescing();
1754 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1755 DEFINING_FILE_FOR(SimpleRegisterCoalescing)