1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "llvm/CodeGen/SimpleRegisterCoalescing.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "VirtRegMap.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
39 STATISTIC(numJoins , "Number of interval joins performed");
40 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
41 STATISTIC(numAborts , "Number of times interval joining aborted");
43 char SimpleRegisterCoalescing::ID = 0;
46 EnableJoining("join-liveintervals",
47 cl::desc("Coalesce copies (default=true)"),
50 RegisterPass<SimpleRegisterCoalescing>
51 X("simple-register-coalescing", "Simple Register Coalescing");
53 // Declare that we implement the RegisterCoalescer interface
54 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
57 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
59 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addPreserved<LiveIntervals>();
61 AU.addPreservedID(PHIEliminationID);
62 AU.addPreservedID(TwoAddressInstructionPassID);
63 AU.addRequired<LiveVariables>();
64 AU.addRequired<LiveIntervals>();
65 AU.addRequired<LoopInfo>();
66 MachineFunctionPass::getAnalysisUsage(AU);
69 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
70 /// being the source and IntB being the dest, thus this defines a value number
71 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
72 /// see if we can merge these two pieces of B into a single value number,
73 /// eliminating a copy. For example:
77 /// B1 = A3 <- this copy
79 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
80 /// value number to be replaced with B0 (which simplifies the B liveinterval).
82 /// This returns true if an interval was modified.
84 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
85 MachineInstr *CopyMI) {
86 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
88 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
90 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
91 VNInfo *BValNo = BLR->valno;
93 // Get the location that B is defined at. Two options: either this value has
94 // an unknown definition point or it is defined at CopyIdx. If unknown, we
96 if (!BValNo->reg) return false;
97 assert(BValNo->def == CopyIdx &&
98 "Copy doesn't define the value?");
100 // AValNo is the value number in A that defines the copy, A0 in the example.
101 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
102 VNInfo *AValNo = AValLR->valno;
104 // If AValNo is defined as a copy from IntB, we can potentially process this.
106 // Get the instruction that defines this value number.
107 unsigned SrcReg = AValNo->reg;
108 if (!SrcReg) return false; // Not defined by a copy.
110 // If the value number is not defined by a copy instruction, ignore it.
112 // If the source register comes from an interval other than IntB, we can't
114 if (rep(SrcReg) != IntB.reg) return false;
116 // Get the LiveRange in IntB that this value number starts with.
117 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
119 // Make sure that the end of the live range is inside the same block as
121 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
123 ValLREndInst->getParent() != CopyMI->getParent()) return false;
125 // Okay, we now know that ValLR ends in the same block that the CopyMI
126 // live-range starts. If there are no intervening live ranges between them in
127 // IntB, we can merge them.
128 if (ValLR+1 != BLR) return false;
130 // If a live interval is a physical register, conservatively check if any
131 // of its sub-registers is overlapping the live interval of the virtual
132 // register. If so, do not coalesce.
133 if (MRegisterInfo::isPhysicalRegister(IntB.reg) &&
134 *mri_->getSubRegisters(IntB.reg)) {
135 for (const unsigned* SR = mri_->getSubRegisters(IntB.reg); *SR; ++SR)
136 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
137 DOUT << "Interfere with sub-register ";
138 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
143 DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
145 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
146 // We are about to delete CopyMI, so need to remove it as the 'instruction
147 // that defines this value #'. Update the the valnum with the new defining
149 BValNo->def = FillerStart;
152 // Okay, we can merge them. We need to insert a new liverange:
153 // [ValLR.end, BLR.begin) of either value number, then we merge the
154 // two value numbers.
155 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
157 // If the IntB live range is assigned to a physical register, and if that
158 // physreg has aliases,
159 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
160 // Update the liveintervals of sub-registers.
161 for (const unsigned *AS = mri_->getSubRegisters(IntB.reg); *AS; ++AS) {
162 LiveInterval &AliasLI = li_->getInterval(*AS);
163 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
164 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
168 // Okay, merge "B1" into the same value number as "B0".
169 if (BValNo != ValLR->valno)
170 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
171 DOUT << " result = "; IntB.print(DOUT, mri_);
174 // If the source instruction was killing the source register before the
175 // merge, unset the isKill marker given the live range has been extended.
176 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
178 ValLREndInst->getOperand(UIdx).unsetIsKill();
180 // Finally, delete the copy instruction.
181 li_->RemoveMachineInstrFromMaps(CopyMI);
182 CopyMI->eraseFromParent();
187 /// AddSubRegIdxPairs - Recursively mark all the registers represented by the
188 /// specified register as sub-registers. The recursion level is expected to be
190 void SimpleRegisterCoalescing::AddSubRegIdxPairs(unsigned Reg, unsigned SubIdx) {
191 std::vector<unsigned> &JoinedRegs = r2rRevMap_[Reg];
192 for (unsigned i = 0, e = JoinedRegs.size(); i != e; ++i) {
193 SubRegIdxes.push_back(std::make_pair(JoinedRegs[i], SubIdx));
194 AddSubRegIdxPairs(JoinedRegs[i], SubIdx);
198 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
199 /// which are the src/dst of the copy instruction CopyMI. This returns true
200 /// if the copy was successfully coalesced away, or if it is never possible
201 /// to coalesce this copy, due to register constraints. It returns
202 /// false if it is not currently possible to coalesce this interval, but
203 /// it may be possible if other things get coalesced.
204 bool SimpleRegisterCoalescing::JoinCopy(MachineInstr *CopyMI,
205 unsigned SrcReg, unsigned DstReg) {
206 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
208 // Get representative registers.
209 unsigned repSrcReg = rep(SrcReg);
210 unsigned repDstReg = rep(DstReg);
212 // If they are already joined we continue.
213 if (repSrcReg == repDstReg) {
214 DOUT << "\tCopy already coalesced.\n";
215 return true; // Not coalescable.
218 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
219 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
221 // If they are both physical registers, we cannot join them.
222 if (SrcIsPhys && DstIsPhys) {
223 DOUT << "\tCan not coalesce physregs.\n";
224 return true; // Not coalescable.
227 // We only join virtual registers with allocatable physical registers.
228 if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
229 DOUT << "\tSrc reg is unallocatable physreg.\n";
230 return true; // Not coalescable.
232 if (DstIsPhys && !allocatableRegs_[repDstReg]) {
233 DOUT << "\tDst reg is unallocatable physreg.\n";
234 return true; // Not coalescable.
237 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
238 unsigned RealDstReg = 0;
240 unsigned SubIdx = CopyMI->getOperand(2).getImm();
242 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
243 // coalesced with AX.
244 repSrcReg = mri_->getSubReg(repSrcReg, SubIdx);
245 else if (DstIsPhys) {
246 // If this is a extract_subreg where dst is a physical register, e.g.
247 // cl = EXTRACT_SUBREG reg1024, 1
248 // then create and update the actual physical register allocated to RHS.
249 const TargetRegisterClass *RC=mf_->getSSARegMap()->getRegClass(repSrcReg);
250 for (const unsigned *SRs = mri_->getSuperRegisters(repDstReg);
251 unsigned SR = *SRs; ++SRs) {
252 if (repDstReg == mri_->getSubReg(SR, SubIdx) &&
258 assert(RealDstReg && "Invalid extra_subreg instruction!");
260 // For this type of EXTRACT_SUBREG, conservatively
261 // check if the live interval of the source register interfere with the
262 // actual super physical register we are trying to coalesce with.
263 LiveInterval &RHS = li_->getInterval(repSrcReg);
264 if (li_->hasInterval(RealDstReg) &&
265 RHS.overlaps(li_->getInterval(RealDstReg))) {
266 DOUT << "Interfere with register ";
267 DEBUG(li_->getInterval(RealDstReg).print(DOUT, mri_));
268 return true; // Not coalescable
270 for (const unsigned* SR = mri_->getSubRegisters(RealDstReg); *SR; ++SR)
271 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
272 DOUT << "Interfere with sub-register ";
273 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
274 return true; // Not coalescable
276 } else if (li_->getInterval(repDstReg).getSize() >
277 li_->getInterval(repSrcReg).getSize()) {
278 // Be conservative. If both sides are virtual registers, do not coalesce
279 // if the sub-register live interval is longer.
282 } else if (differingRegisterClasses(repSrcReg, repDstReg)) {
283 // If they are not of the same register class, we cannot join them.
284 DOUT << "\tSrc/Dest are different register classes.\n";
285 // Allow the coalescer to try again in case either side gets coalesced to
286 // a physical register that's compatible with the other side. e.g.
287 // r1024 = MOV32to32_ r1025
288 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
292 LiveInterval &SrcInt = li_->getInterval(repSrcReg);
293 LiveInterval &DstInt = li_->getInterval(repDstReg);
294 assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
295 "Register mapping is horribly broken!");
297 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
298 DOUT << " and "; DstInt.print(DOUT, mri_);
301 // Check if it is necessary to propagate "isDead" property before intervals
303 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
304 bool isDead = mopd->isDead();
305 bool isShorten = false;
306 unsigned SrcStart = 0, RemoveStart = 0;
307 unsigned SrcEnd = 0, RemoveEnd = 0;
309 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
310 LiveInterval::iterator SrcLR =
311 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
312 RemoveStart = SrcStart = SrcLR->start;
313 RemoveEnd = SrcEnd = SrcLR->end;
314 // The instruction which defines the src is only truly dead if there are
315 // no intermediate uses and there isn't a use beyond the copy.
316 // FIXME: find the last use, mark is kill and shorten the live range.
317 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
321 MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
323 // Shorten the liveinterval to the end of last use.
327 RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
330 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
332 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
334 // A dead def should have a single cycle interval.
341 // We need to be careful about coalescing a source physical register with a
342 // virtual register. Once the coalescing is done, it cannot be broken and
343 // these are not spillable! If the destination interval uses are far away,
344 // think twice about coalescing them!
345 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
346 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
347 unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
348 unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
349 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(JoinVReg);
350 unsigned Threshold = allocatableRCRegs_[RC].count();
352 // If the virtual register live interval is long but it has low use desity,
353 // do not join them, instead mark the physical register as its allocation
355 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
356 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
357 if (Length > Threshold &&
358 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
359 JoinVInt.preference = JoinPReg;
361 DOUT << "\tMay tie down a physical register, abort!\n";
366 // Okay, attempt to join these two intervals. On failure, this returns false.
367 // Otherwise, if one of the intervals being joined is a physreg, this method
368 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
369 // been modified, so we can use this information below to update aliases.
370 bool Swapped = false;
371 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
373 // Result of the copy is dead. Propagate this property.
375 assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
376 "Live-in must be a physical register!");
377 // Live-in to the function but dead. Remove it from entry live-in set.
378 // JoinIntervals may end up swapping the two intervals.
379 mf_->begin()->removeLiveIn(repSrcReg);
381 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
383 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
390 if (isShorten || isDead) {
391 // Shorten the destination live interval.
393 SrcInt.removeRange(RemoveStart, RemoveEnd);
396 // Coalescing failed.
398 // If we can eliminate the copy without merging the live ranges, do so now.
399 if (!isExtSubReg && AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI))
402 // Otherwise, we are unable to join the intervals.
403 DOUT << "Interference!\n";
407 LiveInterval *ResSrcInt = &SrcInt;
408 LiveInterval *ResDstInt = &DstInt;
410 std::swap(repSrcReg, repDstReg);
411 std::swap(ResSrcInt, ResDstInt);
413 assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
414 "LiveInterval::join didn't work right!");
416 // If we're about to merge live ranges into a physical register live range,
417 // we have to update any aliased register's live ranges to indicate that they
418 // have clobbered values for this range.
419 if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
420 // Unset unnecessary kills.
421 if (!ResDstInt->containsOneValue()) {
422 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
423 E = ResSrcInt->end(); I != E; ++I)
424 unsetRegisterKills(I->start, I->end, repDstReg);
427 // If this is a extract_subreg where dst is a physical register, e.g.
428 // cl = EXTRACT_SUBREG reg1024, 1
429 // then create and update the actual physical register allocated to RHS.
431 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
432 SmallSet<const VNInfo*, 4> CopiedValNos;
433 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
434 E = ResSrcInt->ranges.end(); I != E; ++I) {
435 LiveInterval::const_iterator DstLR =
436 ResDstInt->FindLiveRangeContaining(I->start);
437 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
438 const VNInfo *DstValNo = DstLR->valno;
439 if (CopiedValNos.insert(DstValNo)) {
440 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->reg,
441 li_->getVNInfoAllocator());
442 RealDstInt.addKills(ValNo, DstValNo->kills);
443 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
446 repDstReg = RealDstReg;
449 // Update the liveintervals of sub-registers.
450 for (const unsigned *AS = mri_->getSubRegisters(repDstReg); *AS; ++AS)
451 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
452 li_->getVNInfoAllocator());
454 // Merge use info if the destination is a virtual register.
455 LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
456 LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
457 dVI.NumUses += sVI.NumUses;
460 // Remember these liveintervals have been joined.
461 JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
462 if (MRegisterInfo::isVirtualRegister(repDstReg))
463 JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
465 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
467 // Make sure we allocate the larger super-register.
468 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
469 std::swap(repSrcReg, repDstReg);
470 std::swap(ResSrcInt, ResDstInt);
472 unsigned SubIdx = CopyMI->getOperand(2).getImm();
473 SubRegIdxes.push_back(std::make_pair(repSrcReg, SubIdx));
474 AddSubRegIdxPairs(repSrcReg, SubIdx);
477 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, mri_);
480 // repSrcReg is guarateed to be the register whose live interval that is
482 li_->removeInterval(repSrcReg);
483 r2rMap_[repSrcReg] = repDstReg;
484 r2rRevMap_[repDstReg].push_back(repSrcReg);
486 // Finally, delete the copy instruction.
487 li_->RemoveMachineInstrFromMaps(CopyMI);
488 CopyMI->eraseFromParent();
494 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
495 /// compute what the resultant value numbers for each value in the input two
496 /// ranges will be. This is complicated by copies between the two which can
497 /// and will commonly cause multiple value numbers to be merged into one.
499 /// VN is the value number that we're trying to resolve. InstDefiningValue
500 /// keeps track of the new InstDefiningValue assignment for the result
501 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
502 /// whether a value in this or other is a copy from the opposite set.
503 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
504 /// already been assigned.
506 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
507 /// contains the value number the copy is from.
509 static unsigned ComputeUltimateVN(VNInfo *VNI,
510 SmallVector<VNInfo*, 16> &NewVNInfo,
511 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
512 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
513 SmallVector<int, 16> &ThisValNoAssignments,
514 SmallVector<int, 16> &OtherValNoAssignments) {
515 unsigned VN = VNI->id;
517 // If the VN has already been computed, just return it.
518 if (ThisValNoAssignments[VN] >= 0)
519 return ThisValNoAssignments[VN];
520 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
522 // If this val is not a copy from the other val, then it must be a new value
523 // number in the destination.
524 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
525 if (I == ThisFromOther.end()) {
526 NewVNInfo.push_back(VNI);
527 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
529 VNInfo *OtherValNo = I->second;
531 // Otherwise, this *is* a copy from the RHS. If the other side has already
532 // been computed, return it.
533 if (OtherValNoAssignments[OtherValNo->id] >= 0)
534 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
536 // Mark this value number as currently being computed, then ask what the
537 // ultimate value # of the other value is.
538 ThisValNoAssignments[VN] = -2;
539 unsigned UltimateVN =
540 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
541 OtherValNoAssignments, ThisValNoAssignments);
542 return ThisValNoAssignments[VN] = UltimateVN;
545 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
546 return std::find(V.begin(), V.end(), Val) != V.end();
549 /// SimpleJoin - Attempt to joint the specified interval into this one. The
550 /// caller of this method must guarantee that the RHS only contains a single
551 /// value number and that the RHS is not defined by a copy from this
552 /// interval. This returns false if the intervals are not joinable, or it
553 /// joins them and returns true.
554 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
555 assert(RHS.containsOneValue());
557 // Some number (potentially more than one) value numbers in the current
558 // interval may be defined as copies from the RHS. Scan the overlapping
559 // portions of the LHS and RHS, keeping track of this and looking for
560 // overlapping live ranges that are NOT defined as copies. If these exist, we
563 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
564 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
566 if (LHSIt->start < RHSIt->start) {
567 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
568 if (LHSIt != LHS.begin()) --LHSIt;
569 } else if (RHSIt->start < LHSIt->start) {
570 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
571 if (RHSIt != RHS.begin()) --RHSIt;
574 SmallVector<VNInfo*, 8> EliminatedLHSVals;
577 // Determine if these live intervals overlap.
578 bool Overlaps = false;
579 if (LHSIt->start <= RHSIt->start)
580 Overlaps = LHSIt->end > RHSIt->start;
582 Overlaps = RHSIt->end > LHSIt->start;
584 // If the live intervals overlap, there are two interesting cases: if the
585 // LHS interval is defined by a copy from the RHS, it's ok and we record
586 // that the LHS value # is the same as the RHS. If it's not, then we cannot
587 // coalesce these live ranges and we bail out.
589 // If we haven't already recorded that this value # is safe, check it.
590 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
591 // Copy from the RHS?
592 unsigned SrcReg = LHSIt->valno->reg;
593 if (rep(SrcReg) != RHS.reg)
594 return false; // Nope, bail out.
596 EliminatedLHSVals.push_back(LHSIt->valno);
599 // We know this entire LHS live range is okay, so skip it now.
600 if (++LHSIt == LHSEnd) break;
604 if (LHSIt->end < RHSIt->end) {
605 if (++LHSIt == LHSEnd) break;
607 // One interesting case to check here. It's possible that we have
608 // something like "X3 = Y" which defines a new value number in the LHS,
609 // and is the last use of this liverange of the RHS. In this case, we
610 // want to notice this copy (so that it gets coalesced away) even though
611 // the live ranges don't actually overlap.
612 if (LHSIt->start == RHSIt->end) {
613 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
614 // We already know that this value number is going to be merged in
615 // if coalescing succeeds. Just skip the liverange.
616 if (++LHSIt == LHSEnd) break;
618 // Otherwise, if this is a copy from the RHS, mark it as being merged
620 if (rep(LHSIt->valno->reg) == RHS.reg) {
621 EliminatedLHSVals.push_back(LHSIt->valno);
623 // We know this entire LHS live range is okay, so skip it now.
624 if (++LHSIt == LHSEnd) break;
629 if (++RHSIt == RHSEnd) break;
633 // If we got here, we know that the coalescing will be successful and that
634 // the value numbers in EliminatedLHSVals will all be merged together. Since
635 // the most common case is that EliminatedLHSVals has a single number, we
636 // optimize for it: if there is more than one value, we merge them all into
637 // the lowest numbered one, then handle the interval as if we were merging
638 // with one value number.
640 if (EliminatedLHSVals.size() > 1) {
641 // Loop through all the equal value numbers merging them into the smallest
643 VNInfo *Smallest = EliminatedLHSVals[0];
644 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
645 if (EliminatedLHSVals[i]->id < Smallest->id) {
646 // Merge the current notion of the smallest into the smaller one.
647 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
648 Smallest = EliminatedLHSVals[i];
650 // Merge into the smallest.
651 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
656 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
657 LHSValNo = EliminatedLHSVals[0];
660 // Okay, now that there is a single LHS value number that we're merging the
661 // RHS into, update the value number info for the LHS to indicate that the
662 // value number is defined where the RHS value number was.
663 const VNInfo *VNI = RHS.getValNumInfo(0);
664 LHSValNo->def = VNI->def;
665 LHSValNo->reg = VNI->reg;
667 // Okay, the final step is to loop over the RHS live intervals, adding them to
669 LHS.addKills(LHSValNo, VNI->kills);
670 LHS.MergeRangesInAsValue(RHS, LHSValNo);
671 LHS.weight += RHS.weight;
672 if (RHS.preference && !LHS.preference)
673 LHS.preference = RHS.preference;
678 /// JoinIntervals - Attempt to join these two intervals. On failure, this
679 /// returns false. Otherwise, if one of the intervals being joined is a
680 /// physreg, this method always canonicalizes LHS to be it. The output
681 /// "RHS" will not have been modified, so we can use this information
682 /// below to update aliases.
683 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
684 LiveInterval &RHS, bool &Swapped) {
685 // Compute the final value assignment, assuming that the live ranges can be
687 SmallVector<int, 16> LHSValNoAssignments;
688 SmallVector<int, 16> RHSValNoAssignments;
689 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
690 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
691 SmallVector<VNInfo*, 16> NewVNInfo;
693 // If a live interval is a physical register, conservatively check if any
694 // of its sub-registers is overlapping the live interval of the virtual
695 // register. If so, do not coalesce.
696 if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
697 *mri_->getSubRegisters(LHS.reg)) {
698 for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
699 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
700 DOUT << "Interfere with sub-register ";
701 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
704 } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
705 *mri_->getSubRegisters(RHS.reg)) {
706 for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
707 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
708 DOUT << "Interfere with sub-register ";
709 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
714 // Compute ultimate value numbers for the LHS and RHS values.
715 if (RHS.containsOneValue()) {
716 // Copies from a liveinterval with a single value are simple to handle and
717 // very common, handle the special case here. This is important, because
718 // often RHS is small and LHS is large (e.g. a physreg).
720 // Find out if the RHS is defined as a copy from some value in the LHS.
721 int RHSVal0DefinedFromLHS = -1;
723 VNInfo *RHSValNoInfo = NULL;
724 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
725 unsigned RHSSrcReg = RHSValNoInfo0->reg;
726 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
727 // If RHS is not defined as a copy from the LHS, we can use simpler and
728 // faster checks to see if the live ranges are coalescable. This joiner
729 // can't swap the LHS/RHS intervals though.
730 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
731 return SimpleJoin(LHS, RHS);
733 RHSValNoInfo = RHSValNoInfo0;
736 // It was defined as a copy from the LHS, find out what value # it is.
737 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
738 RHSValID = RHSValNoInfo->id;
739 RHSVal0DefinedFromLHS = RHSValID;
742 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
743 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
744 NewVNInfo.resize(LHS.getNumValNums(), NULL);
746 // Okay, *all* of the values in LHS that are defined as a copy from RHS
747 // should now get updated.
748 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
751 unsigned VN = VNI->id;
752 if (unsigned LHSSrcReg = VNI->reg) {
753 if (rep(LHSSrcReg) != RHS.reg) {
754 // If this is not a copy from the RHS, its value number will be
755 // unmodified by the coalescing.
757 LHSValNoAssignments[VN] = VN;
758 } else if (RHSValID == -1) {
759 // Otherwise, it is a copy from the RHS, and we don't already have a
760 // value# for it. Keep the current value number, but remember it.
761 LHSValNoAssignments[VN] = RHSValID = VN;
762 NewVNInfo[VN] = RHSValNoInfo;
763 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
765 // Otherwise, use the specified value #.
766 LHSValNoAssignments[VN] = RHSValID;
767 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
768 NewVNInfo[VN] = RHSValNoInfo;
769 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
774 LHSValNoAssignments[VN] = VN;
778 assert(RHSValID != -1 && "Didn't find value #?");
779 RHSValNoAssignments[0] = RHSValID;
780 if (RHSVal0DefinedFromLHS != -1) {
781 // This path doesn't go through ComputeUltimateVN so just set
783 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
786 // Loop over the value numbers of the LHS, seeing if any are defined from
788 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
791 unsigned ValSrcReg = VNI->reg;
792 if (ValSrcReg == 0) // Src not defined by a copy?
795 // DstReg is known to be a register in the LHS interval. If the src is
796 // from the RHS interval, we can use its value #.
797 if (rep(ValSrcReg) != RHS.reg)
800 // Figure out the value # from the RHS.
801 LHSValsDefinedFromRHS[VNI] = RHS.getLiveRangeContaining(VNI->def-1)->valno;
804 // Loop over the value numbers of the RHS, seeing if any are defined from
806 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
809 unsigned ValSrcReg = VNI->reg;
810 if (ValSrcReg == 0) // Src not defined by a copy?
813 // DstReg is known to be a register in the RHS interval. If the src is
814 // from the LHS interval, we can use its value #.
815 if (rep(ValSrcReg) != LHS.reg)
818 // Figure out the value # from the LHS.
819 RHSValsDefinedFromLHS[VNI]= LHS.getLiveRangeContaining(VNI->def-1)->valno;
822 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
823 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
824 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
826 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
829 unsigned VN = VNI->id;
830 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
832 ComputeUltimateVN(VNI, NewVNInfo,
833 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
834 LHSValNoAssignments, RHSValNoAssignments);
836 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
839 unsigned VN = VNI->id;
840 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
842 // If this value number isn't a copy from the LHS, it's a new number.
843 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
844 NewVNInfo.push_back(VNI);
845 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
849 ComputeUltimateVN(VNI, NewVNInfo,
850 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
851 RHSValNoAssignments, LHSValNoAssignments);
855 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
856 // interval lists to see if these intervals are coalescable.
857 LiveInterval::const_iterator I = LHS.begin();
858 LiveInterval::const_iterator IE = LHS.end();
859 LiveInterval::const_iterator J = RHS.begin();
860 LiveInterval::const_iterator JE = RHS.end();
862 // Skip ahead until the first place of potential sharing.
863 if (I->start < J->start) {
864 I = std::upper_bound(I, IE, J->start);
865 if (I != LHS.begin()) --I;
866 } else if (J->start < I->start) {
867 J = std::upper_bound(J, JE, I->start);
868 if (J != RHS.begin()) --J;
872 // Determine if these two live ranges overlap.
874 if (I->start < J->start) {
875 Overlaps = I->end > J->start;
877 Overlaps = J->end > I->start;
880 // If so, check value # info to determine if they are really different.
882 // If the live range overlap will map to the same value number in the
883 // result liverange, we can still coalesce them. If not, we can't.
884 if (LHSValNoAssignments[I->valno->id] !=
885 RHSValNoAssignments[J->valno->id])
889 if (I->end < J->end) {
898 // Update kill info. Some live ranges are extended due to copy coalescing.
899 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
900 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
901 VNInfo *VNI = I->first;
902 unsigned LHSValID = LHSValNoAssignments[VNI->id];
903 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
904 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
907 // Update kill info. Some live ranges are extended due to copy coalescing.
908 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
909 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
910 VNInfo *VNI = I->first;
911 unsigned RHSValID = RHSValNoAssignments[VNI->id];
912 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
913 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
916 // If we get here, we know that we can coalesce the live ranges. Ask the
917 // intervals to coalesce themselves now.
918 if ((RHS.ranges.size() > LHS.ranges.size() &&
919 MRegisterInfo::isVirtualRegister(LHS.reg)) ||
920 MRegisterInfo::isPhysicalRegister(RHS.reg)) {
921 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
924 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
931 // DepthMBBCompare - Comparison predicate that sort first based on the loop
932 // depth of the basic block (the unsigned), and then on the MBB number.
933 struct DepthMBBCompare {
934 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
935 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
936 if (LHS.first > RHS.first) return true; // Deeper loops first
937 return LHS.first == RHS.first &&
938 LHS.second->getNumber() < RHS.second->getNumber();
943 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
944 std::vector<CopyRec> &TryAgain) {
945 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
947 std::vector<CopyRec> VirtCopies;
948 std::vector<CopyRec> PhysCopies;
949 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
951 MachineInstr *Inst = MII++;
953 // If this isn't a copy nor a extract_subreg, we can't join intervals.
954 unsigned SrcReg, DstReg;
955 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
956 DstReg = Inst->getOperand(0).getReg();
957 SrcReg = Inst->getOperand(1).getReg();
958 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
961 unsigned repSrcReg = rep(SrcReg);
962 unsigned repDstReg = rep(DstReg);
963 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
964 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
965 if (SrcIsPhys || DstIsPhys)
966 PhysCopies.push_back(getCopyRec(Inst, SrcReg, DstReg));
968 VirtCopies.push_back(getCopyRec(Inst, SrcReg, DstReg));
971 // Try coalescing physical register + virtual register first.
972 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
973 CopyRec &TheCopy = PhysCopies[i];
974 if (!JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg))
975 TryAgain.push_back(TheCopy);
977 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
978 CopyRec &TheCopy = VirtCopies[i];
979 if (!JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg))
980 TryAgain.push_back(TheCopy);
984 void SimpleRegisterCoalescing::joinIntervals() {
985 DOUT << "********** JOINING INTERVALS ***********\n";
987 JoinedLIs.resize(li_->getNumIntervals());
990 std::vector<CopyRec> TryAgainList;
991 const LoopInfo &LI = getAnalysis<LoopInfo>();
992 if (LI.begin() == LI.end()) {
993 // If there are no loops in the function, join intervals in function order.
994 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
996 CopyCoalesceInMBB(I, TryAgainList);
998 // Otherwise, join intervals in inner loops before other intervals.
999 // Unfortunately we can't just iterate over loop hierarchy here because
1000 // there may be more MBB's than BB's. Collect MBB's for sorting.
1002 // Join intervals in the function prolog first. We want to join physical
1003 // registers with virtual registers before the intervals got too long.
1004 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1005 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); I != E;++I)
1006 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1008 // Sort by loop depth.
1009 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1011 // Finally, join intervals in loop nest order.
1012 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1013 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1016 // Joining intervals can allow other intervals to be joined. Iteratively join
1017 // until we make no progress.
1018 bool ProgressMade = true;
1019 while (ProgressMade) {
1020 ProgressMade = false;
1022 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1023 CopyRec &TheCopy = TryAgainList[i];
1025 JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1026 TheCopy.MI = 0; // Mark this one as done.
1027 ProgressMade = true;
1032 // Some live range has been lengthened due to colaescing, eliminate the
1033 // unnecessary kills.
1034 int RegNum = JoinedLIs.find_first();
1035 while (RegNum != -1) {
1036 unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
1037 unsigned repReg = rep(Reg);
1038 LiveInterval &LI = li_->getInterval(repReg);
1039 LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
1040 for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
1041 MachineInstr *Kill = svi.Kills[i];
1042 // Suppose vr1 = op vr2, x
1043 // and vr1 and vr2 are coalesced. vr2 should still be marked kill
1044 // unless it is a two-address operand.
1045 if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
1047 if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
1048 unsetRegisterKill(Kill, repReg);
1050 RegNum = JoinedLIs.find_next(RegNum);
1053 DOUT << "*** Register mapping ***\n";
1054 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1056 DOUT << " reg " << i << " -> ";
1057 DEBUG(printRegName(r2rMap_[i]));
1062 /// Return true if the two specified registers belong to different register
1063 /// classes. The registers may be either phys or virt regs.
1064 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1065 unsigned RegB) const {
1067 // Get the register classes for the first reg.
1068 if (MRegisterInfo::isPhysicalRegister(RegA)) {
1069 assert(MRegisterInfo::isVirtualRegister(RegB) &&
1070 "Shouldn't consider two physregs!");
1071 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1074 // Compare against the regclass for the second reg.
1075 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1076 if (MRegisterInfo::isVirtualRegister(RegB))
1077 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1079 return !RegClass->contains(RegB);
1082 /// lastRegisterUse - Returns the last use of the specific register between
1083 /// cycles Start and End. It also returns the use operand by reference. It
1084 /// returns NULL if there are no uses.
1086 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
1087 MachineOperand *&MOU) {
1088 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1091 // Skip deleted instructions
1092 MachineInstr *MI = li_->getInstructionFromIndex(e);
1093 while ((e - InstrSlots::NUM) >= s && !MI) {
1094 e -= InstrSlots::NUM;
1095 MI = li_->getInstructionFromIndex(e);
1097 if (e < s || MI == NULL)
1100 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1101 MachineOperand &MO = MI->getOperand(i);
1102 if (MO.isRegister() && MO.isUse() && MO.getReg() &&
1103 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1109 e -= InstrSlots::NUM;
1116 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1117 /// register. It returns NULL if the def is not found.
1118 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
1119 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1120 MachineOperand &MO = MI->getOperand(i);
1121 if (MO.isRegister() && MO.isDef() &&
1122 mri_->regsOverlap(rep(MO.getReg()), Reg))
1128 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1129 /// of the specific instruction.
1130 void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1131 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1132 MachineOperand &MO = MI->getOperand(i);
1133 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1134 mri_->regsOverlap(rep(MO.getReg()), Reg))
1139 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1140 /// between cycles Start and End.
1141 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1143 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1146 // Skip deleted instructions
1147 MachineInstr *MI = li_->getInstructionFromIndex(e);
1148 while ((e - InstrSlots::NUM) >= s && !MI) {
1149 e -= InstrSlots::NUM;
1150 MI = li_->getInstructionFromIndex(e);
1152 if (e < s || MI == NULL)
1155 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1156 MachineOperand &MO = MI->getOperand(i);
1157 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1158 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1163 e -= InstrSlots::NUM;
1167 /// hasRegisterDef - True if the instruction defines the specific register.
1169 bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1170 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1171 MachineOperand &MO = MI->getOperand(i);
1172 if (MO.isRegister() && MO.isDef() &&
1173 mri_->regsOverlap(rep(MO.getReg()), Reg))
1179 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1180 if (MRegisterInfo::isPhysicalRegister(reg))
1181 cerr << mri_->getName(reg);
1183 cerr << "%reg" << reg;
1186 void SimpleRegisterCoalescing::releaseMemory() {
1187 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1188 r2rRevMap_[i].clear();
1192 SubRegIdxes.clear();
1195 static bool isZeroLengthInterval(LiveInterval *li) {
1196 for (LiveInterval::Ranges::const_iterator
1197 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1198 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1203 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1205 tm_ = &fn.getTarget();
1206 mri_ = tm_->getRegisterInfo();
1207 tii_ = tm_->getInstrInfo();
1208 li_ = &getAnalysis<LiveIntervals>();
1209 lv_ = &getAnalysis<LiveVariables>();
1211 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1212 << "********** Function: "
1213 << ((Value*)mf_->getFunction())->getName() << '\n';
1215 allocatableRegs_ = mri_->getAllocatableSet(fn);
1216 for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1217 E = mri_->regclass_end(); I != E; ++I)
1218 allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1220 SSARegMap *RegMap = mf_->getSSARegMap();
1221 r2rMap_.grow(RegMap->getLastVirtReg());
1222 r2rRevMap_.grow(RegMap->getLastVirtReg());
1224 // Join (coalesce) intervals if requested.
1225 if (EnableJoining) {
1227 DOUT << "********** INTERVALS POST JOINING **********\n";
1228 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1229 I->second.print(DOUT, mri_);
1233 // Transfer sub-registers info to SSARegMap now that coalescing information
1235 while (!SubRegIdxes.empty()) {
1236 std::pair<unsigned, unsigned> RI = SubRegIdxes.back();
1237 SubRegIdxes.pop_back();
1238 mf_->getSSARegMap()->setIsSubRegister(RI.first, rep(RI.first), RI.second);
1242 // perform a final pass over the instructions and compute spill
1243 // weights, coalesce virtual registers and remove identity moves.
1244 const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
1246 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1247 mbbi != mbbe; ++mbbi) {
1248 MachineBasicBlock* mbb = mbbi;
1249 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
1251 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1253 // if the move will be an identity move delete it
1254 unsigned srcReg, dstReg, RegRep;
1255 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1256 (RegRep = rep(srcReg)) == rep(dstReg)) {
1257 // remove from def list
1258 LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1259 MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1260 // If def of this move instruction is dead, remove its live range from
1261 // the dstination register's live interval.
1263 unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1264 LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1265 RegInt.removeRange(MLR->start, MoveIdx+1);
1267 li_->removeInterval(RegRep);
1269 li_->RemoveMachineInstrFromMaps(mii);
1270 mii = mbbi->erase(mii);
1273 SmallSet<unsigned, 4> UniqueUses;
1274 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1275 const MachineOperand &mop = mii->getOperand(i);
1276 if (mop.isRegister() && mop.getReg() &&
1277 MRegisterInfo::isVirtualRegister(mop.getReg())) {
1278 // replace register with representative register
1279 unsigned OrigReg = mop.getReg();
1280 unsigned reg = rep(OrigReg);
1281 // Don't rewrite if it is a sub-register of a virtual register.
1282 if (!RegMap->isSubRegister(OrigReg))
1283 mii->getOperand(i).setReg(reg);
1284 else if (MRegisterInfo::isPhysicalRegister(reg))
1285 mii->getOperand(i).setReg(mri_->getSubReg(reg,
1286 RegMap->getSubRegisterIndex(OrigReg)));
1288 // Multiple uses of reg by the same instruction. It should not
1289 // contribute to spill weight again.
1290 if (UniqueUses.count(reg) != 0)
1292 LiveInterval &RegInt = li_->getInterval(reg);
1293 float w = (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
1295 UniqueUses.insert(reg);
1303 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1304 LiveInterval &LI = I->second;
1305 if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1306 // If the live interval length is essentially zero, i.e. in every live
1307 // range the use follows def immediately, it doesn't make sense to spill
1308 // it and hope it will be easier to allocate for this li.
1309 if (isZeroLengthInterval(&LI))
1310 LI.weight = HUGE_VALF;
1312 // Slightly prefer live interval that has been assigned a preferred reg.
1316 // Divide the weight of the interval by its size. This encourages
1317 // spilling of intervals that are large and have few uses, and
1318 // discourages spilling of small intervals with many uses.
1319 LI.weight /= LI.getSize();
1327 /// print - Implement the dump method.
1328 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1332 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1333 return new SimpleRegisterCoalescing();
1336 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1337 DEFINING_FILE_FOR(SimpleRegisterCoalescing)